Lesson 6 of 18 The System Calls

socket() and bind() in C

Create sockets with socket() and attach them to a local address and port with bind(). Covers SO_REUSEADDR, 'Address already in use' and port 0.

30-40 min beginner 0/18 lessons done
Course contents Lesson 6 of 18 · 0 done
On this page (9 sections)
  1. What you will learn
  2. socket(): get a descriptor
  3. bind(): claim a local address and port
  4. Address already in use” and SO_REUSEADDR
  5. Port 0: let the kernel choose
  6. Common bind() errors
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will learn

  • What socket() returns and what its three arguments mean.
  • When you need bind() and when the kernel binds for you.
  • How to fix “Address already in use” with SO_REUSEADDR.
  • How to let the OS pick a free port and find out which one it chose.

socket(): get a descriptor

#include <sys/types.h>
#include <sys/socket.h>

int socket(int domain, int type, int protocol);
ArgumentValuesMeaning
domainAF_INET, AF_INET6, AF_UNIXAddress family the socket will use
typeSOCK_STREAM, SOCK_DGRAM, SOCK_RAWStream (TCP), datagram (UDP), raw
protocol0Pick the default protocol for this family and type

It returns a new file descriptor, or -1 with errno set (for example EAFNOSUPPORT if the machine has IPv6 disabled).

A freshly created socket has no address and no peer. It is just a handle. In modern code, you don’t hard-code the arguments; you pass the values from a getaddrinfo() result:

int fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd == -1) {
    perror("socket");
    /* try the next addrinfo entry */
}

On Linux you can OR SOCK_NONBLOCK or SOCK_CLOEXEC into type to set those options atomically at creation.

bind(): claim a local address and port

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

bind() attaches the socket to a local IP address and port. Returns 0 or -1 with errno.

Servers must bind: clients need to know which port to reach. Clients almost never call bind(). When a client calls connect() (or sendto() on UDP) on an unbound socket, the kernel picks the right local address for the route and an ephemeral port automatically.

The usual server setup with getaddrinfo():

struct addrinfo hints, *res, *ai;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;            /* wildcard address */
getaddrinfo(NULL, "5050", &hints, &res);

int fd = -1;
for (ai = res; ai != NULL; ai = ai->ai_next) {
    fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
    if (fd == -1)
        continue;
    if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0)
        break;                          /* bound */
    close(fd);
    fd = -1;
}
freeaddrinfo(res);

“Address already in use” and SO_REUSEADDR

Start a TCP server, connect to it, stop the server with Ctrl-C, and start it again straight away. Very often bind() fails with EADDRINUSE.

That’s because the side that closes a TCP connection first keeps it in the TIME_WAIT state for a while (commonly 60 seconds on Linux, up to a few minutes elsewhere) so that stray late packets from the old connection can’t be mistaken for a new one. While any connection on that port lingers, a plain bind() refuses.

The fix every server uses is to set SO_REUSEADDR before bind():

int on = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on) == -1) {
    perror("setsockopt");
    exit(1);
}

This allows binding while old connections sit in TIME_WAIT. It does not let two live servers share one port on Linux; that’s a separate option, SO_REUSEPORT, used for load-spreading across processes.

If EADDRINUSE persists, something really is listening there. ss -ltnp | grep 5050 (or lsof -i :5050 on macOS) shows which process.

Port 0: let the kernel choose

Binding to port 0 asks the kernel for any free port. That’s useful in tests where several servers run in parallel. Use getsockname() to discover the port it picked:

struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(0);               /* any free port */
bind(fd, (struct sockaddr *)&addr, sizeof addr);

socklen_t len = sizeof addr;
getsockname(fd, (struct sockaddr *)&addr, &len);
printf("listening on port %u\n", ntohs(addr.sin_port));

Common bind() errors

errnoCauseFix
EADDRINUSEPort busy or in TIME_WAITSO_REUSEADDR, or find the other process
EACCESPort below 1024 without privilegesUse a higher port, or grant CAP_NET_BIND_SERVICE
EADDRNOTAVAILThe IP address isn’t on this machineBind to the wildcard or an address the host owns
EINVALSocket already boundBind only once

Key takeaways

  • socket() returns an unbound descriptor; take its arguments from getaddrinfo().
  • Servers bind to a known port; clients let connect() bind implicitly.
  • Set SO_REUSEADDR before bind() on every TCP server so restarts don’t fail.
  • Bind to port 0 for “any free port” and read the result with getsockname().

Exercises

  1. Write a server skeleton without SO_REUSEADDR, reproduce the EADDRINUSE error after a restart, then add the option and confirm it’s gone.
  2. Bind to port 0 three times in one program and print the three ports chosen.
  3. Try to bind to port 80 as a normal user and print strerror(errno).

Quiz

  1. Why does a typical TCP client not call bind()?
  2. What problem does SO_REUSEADDR solve?
  3. How do you find which port the kernel picked after binding to port 0?
Show answers
  1. connect() binds the socket automatically to a suitable local address and an ephemeral port; the client’s port number doesn’t need to be known in advance.
  2. It lets a server bind its port again while old connections on that port are still in TIME_WAIT, so restarts don’t fail with “Address already in use”.
  3. Call getsockname() on the socket and read the port (with ntohs()).

Finished this lesson?

Mark it complete to track your progress (saved in this browser).