Since a lot of the higher-level libraries, such as the MQTT library and the CoAP library, entail using sockets and the socket API directly, we will cover some of the most common function calls.
As stated in the previous topic, we will be using Zephyr’s BSD Sockets API, which will then be offloaded to the Modem library socket API.
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:
Below we see the socket families, types and protocols that are currently supported in the nRF9160 modem.
Although we don’t recommend using the Modem Library socket API directly, it is a useful reference to see which socket families, types and protocols are supported with the nRF9160 modem.
Please be aware that the Modem Library socket API won’t always match the BSD Sockets API
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.
Socket type: Specifies the semantics of communication. SOCK_STREAM is used for TCP connections and SOCK_DGRAM is used for UDP connections.
Socket protocol: Specifies the transport protocol to be used with the socket.
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 is the socket file descriptor int sock, to be used in other socket operations to refer to the 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/DTLS for a socket, which we will see in Lesson 5 Exercise 2.
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
Let’s break down the function parameters, simply put:
hostname (nodename)– either a domain name, such as “google.com”, an address string, such as “126.96.36.1992”, 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
struct addrinfo has the following signature
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 connectionless 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 (found in Socket polling API)
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.
The modem library socket API sets errno‘s as defined in <install_path>\nrfx\nrf_modem\include\nrf_errno.h.
Then when offloading sockets, 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
This is the standard that the socket API is adhering to, and more information about the API can be found here. However, due to hardware restrictions on the nRF9160 modem, not all API’s are implemented and it is good practice to refer to the Modem Library for an overview of what is supported and not.