Feedback
Feedback

If you are having issues with the exercises, please create a ticket on DevZone: devzone.nordicsemi.com
Click or drag files to this area to upload. You can upload up to 2 files.

Socket API

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.

Note

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.

Important

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 “81.24.249.2072”, 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.

#define SERVER_HOSTNAME "example.com"
#define SERVER_PORT "80"

struct addrinfo *result;
struct addrinfo hints = {
	.ai_family = AF_INET,
	.ai_socktype = SOCK_STREAM
};

getaddrinfo(SERVER_HOSTNAME, SERVER_PORT, &hints, &result);

Note

Since the domain example.com supports multiple services (IPv4 and IPv6) we pass the hints parameter specifying the socket family, to ensure we get the correct socket address.

After we have called getaddrinfo(), we need to get the relevant information from result and assign it to a variable of type sockaddr_in, the sockaddr structure to use for IPv4 addresses.

First we define the variable server of type struct sockaddr_storage and then the pointer server4 of type struct sockaddr_in which points to the contents of server.

The reason for using struct sockaddr_storage instead of just struct sockaddr is that it supports protocol-family independence and is recommended practice.

struct sockaddr_storage server;
struct sockaddr_in * server4 = ((struct sockaddr_in *)&server);

server4->sin_addr.s_addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr.s_addr;
server4->sin_family = AF_INET;
server4->sin_port = ((struct sockaddr_in *)result->ai_addr)->sin_port;
  • 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.

Connecting

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).

Note

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

connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_in));

Sending

You can send a message on a connected socket using send(), which has the following signature

char message[1024] = {"Hello\0"};
send(sock, message, sizeof(message), 0);

When using datagram sockets with UDP, you can also use sendto(), instead of calling connect() and then send().

char message[1024] = {"Hello\0"};
sendto(sock, message, sizeof(message), (struct sockaddr *)&server, sizeof(struct sockaddr_in));

Receiving

You can receive a message on a connected socket using recv(), which has the following signature

static uint8_t recv_buf[MESSAGE_SIZE];
recv(sock, recv_buf, sizeof(recv_buf), 0);

Polling

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.

static struct pollfd fds;
fds.fd = sock;
fds.events = POLLIN;

int err = poll(&fds, ARRAYSIZE(fds), -1);
if (err < 0) {
	LOG_ERR("poll: %d", errno);
	break;
}

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.

if ((fds.revents & POLLERR) == POLLERR) {
	LOG_ERR("POLLERR");
	break;
}

if ((fds.revents & POLLNVAL) == POLLNVAL) {
	LOG_ERR("POLLNVAL");
	break;
}

if ((fds.revents & POLLHUP) == POLLHUP) {
	LOG_ERR("POLLHUP");
	break;
}

if ((fds.revents & POLLIN) == POLLIN) {
	err = recv(sock, recv_buf, sizeof(recv_buf), 0);
}

Closing

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.

close(sock);

Errors

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
  • Newlib (CONFIG_NEWLIB_LIBC): errors found here

Note

Notice that most of the signatures contain “See POSIX.1-2017 article for normative description.”

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.

Register an account
Already have an account? Log in
(All fields are required unless specified optional)

  • 8 or more characters
  • Upper and lower case letters
  • At least one number or special character

Forgot your password?
Enter the email associated with your account, and we will send you a link to reset your password.