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

The nRF Connect SDK uses Zephyr’s BSD Sockets API as its socket API.

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.

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.

Notice that most of the signatures contain “See POSIX.1-2017 article for normative description.” This is the standard that the socket API adheres to, and more information about the API can also be found here.

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_DGRAM is 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 “81.24.249.2072”, or NULL
  • Service (servname): either a port number passed as a string, such as “80”, a service name, such as “echo”., or NULL.
  • Hints: hints concerning the desired return information, either the structure addrinfo with the type of service requested, or NULL
  • Result (res): pointer to a structure addrinfo containing the information requested

Zero or one of the arguments hostname and servname may be NULL.

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 the 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 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

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

Binding

On the server side of things, after creating the socket descriptor using socket(), we must bind the socket to a local network address for it to be accessible from the network. bind() has the following signature

Listening

Once bound to a specific IP and port, we want to listen for incoming connection requests on that socket, using listen() which has the following signature

To accept a client connection request on a listening socket, use accept(), which has the following signature

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 two most common event flags are POLLIN and POLLOUT (see below). The last field, revents, is filled by poll(), and is also a bitmask of event flags. The three most common are listed below.

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

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