The structure of the socket is determined by the API used for the networking architecture. Internet sockets are commonly based on the Berkeley sockets API, also known as BSD sockets.
Enabling the configuration CONFIG_NET_SOCKETS_POSIX_NAMES, exposes all functions without the zsock_ prefix, which is how we will be referring to them throughout this course.
Creating a socket
When creating a socket, you need to specify the socket family, the socket type, and the socket protocol.
You can create a socket using the API function socket(), which has the following signature:
Let’s briefly explain the three parameters passed to the socket() function.
Socket family: Specifies an address family in which addresses specified in later socket operations should be interpreted. AF_INET for IPv4 and AF_INET6 for IPv6.
Socket type: Specifies the semantics of communication. SOCK_STREAM is used for TCP connections and SOCK_DGRAMis used for UDP connections.
Socket protocol: Specifies the transport protocol to be used with the socket. IPPROTO_TCP for TCP connections and IPPROTO_UDP for UDP connections.
The following code snippet creates a datagram socket in the IPv4 family that uses UDP.
static int sock;
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
If the function is completed successfully, it will return a non-negative integer which will be stored in the socket file descriptor int sock. This is to be used in other socket operations to refer to that socket.
Setting socket options
To set socket options, use the API function setsockopt(), which has the following signature
This function is used, for instance, when configuring TLS and DTLS for a socket, which we will see in Lesson 4 and 5.
Get socket address
To connect a socket, you need the socket address of the peer you want the socket to connect to.
You can obtain the address using the function getaddrinfo(), which has the following signature
Hostname (nodename): either a domain name, such as “google.com”, an address string, such as “184.108.40.2062”, or NULL
Service (servname): either a port number passed as a string, such as “80”, or a service name, such as “echo”.
Hints: either the structure addrinfo with the type of service requested, or NULL
Result (res): pointer to a structure addrinfo containing the information requested
Note here that getaddrinfo() can return multiple results in the form of a linked list in which struct addrinfo res is the first element in the list and the member struct addrinfo * ai_next points to the next element in the list of results.
The following code snippet resolves the address of example.com.
Address: We cast sockaddr * ai_addr, in result to a pointer of type sockaddr_in and retrieve the address.
Family: We know the socket family is IPv4, because that’s what we passed as a hint to getaddrinfo().
Port: We again cast sockaddr * ai_addr, in result, to a pointer of type sockaddr_in and retrieve the port.
To connect a socket use the API function connect(), which has the following signature
Notice that this function takes the address information as struct sockaddr. This is a generic socket address structure, used in most of the socket function calls with addresses, to support both IPv4 and IPv6.
When calling this function, you need to cast the address information you have (usually struct sockaddr_in for IPv4 or struct sockaddr_in6 for IPv6) to the generic struct sockaddr. Then pass the length of the address struct, in our case sizeof(struct sockaddr_in).
Since UDP is a connection-less protocol, connect() doesn’t actually connect a UDP socket, it just tells the socket which address to send to. You can also use sendto() to specify the destination address when sending instead of calling connect(), see below.
The function below connects the socket with the file descriptor sock to the server with the information found in sockaddr_storage server from the previous step. The last parameter addrlen
If you have multiple sockets you want to listen to simultaneously, you can use poll() to poll multiple sockets for events, then call recv() only when there is data to be read.
The function poll(), which has the following signature
This function takes an array of struct pollfd, one for each socket to monitor, the number of elements in the array and a timeout in milliseconds. struct pollfd has the following signature
Set the field fd to the socket file descriptor you want to poll (recall the return value from socket(), int sock), and the field events to a bitmask OR’ing the event flags you want to monitor. In the events field, the Modem library supports the two event flags POLLIN and POLLOUT (see below). The last field, revents, is filled by poll(), and is also a bitmask of event flags. In this case, the full list of event flags below is supported
POLLIN – there is data to be read from the socket
POLLOUT – data can be written to the socket
(revents only) POLLERR – an error has occurred
(revents only) POLLHUP – the device has been disconnected
(revents only) POLLNVAL – invalid fd member
Calling poll() will block until an event specified in events occurs on any of the monitored sockets, or the function times out, based on the timeout parameter.
Note that poll() will set the POLLHUP, POLLERR, and POLLNVAL flag in revents if the condition is true, even if the corresponding bit is not set in the events fields.
The following code snippet polls the socket sock for the event POLLIN with timeout -1, meaning it will block until the event occurs or the call is interrupted.
Successful completion is indicated by a non-negative return value, in which case we can examine the revents field for error flags. Lastly, check that POLLIN flag is set, i.e that the function didn’t just return due to timing out, and then call recv() to read the data.
You can close a socket using close(), which has the following signature
Closing a socket shuts down the socket associated with the socket descriptor and frees the resources allocated to the socket. It’s always good practice to close a socket at the end of an application, or if an error occurs.
If a function call from the socket API fails, most of them will not actually return the error but rather return -1 and then set the global variable errno to the relevant error.
These errno‘s get converted to errno‘s that adhere to the selected C library implementation:
(default) Libc minimal: errors found here: <install_path>\zephyr\lib\libc\minimal\include\errno.h