Networking in C · beginner · ~8 min

bind() — claim a local port

Bind a server socket to a local address and port.

Lesson

What bind() does

The call looks like this:

bind(fd, &addr, sizeof addr);

It tells the kernel: "this socket owns port N on address A." Here fd is the socket's file descriptor (the integer that identifies an open socket).

After a successful bind(), any packet sent to that (address, port) pair is routed to this socket.

Common errors

EADDRINUSE — the address is already in use.

This happens when another process is already bound to the port. It can also happen on your own program: a previous run may have left a socket in the TIME_WAIT state, which briefly holds the port.

To allow rebinding immediately, set the SO_REUSEADDR socket option:

int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

EACCES — permission denied.

Ports below 1024 are privileged and require root. For your labs, pick a high port such as 8080.

Code examples

#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    int yes = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

    struct sockaddr_in a; memset(&a, 0, sizeof a);
    a.sin_family      = AF_INET;
    a.sin_port        = htons(8080);
    a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    if (bind(fd, (struct sockaddr *)&a, sizeof a) < 0) { perror("bind"); return 1; }
    printf("bound to 127.0.0.1:8080\n");
    close(fd);
    return 0;
}

Common mistakes

  • Skipping SO_REUSEADDR. Your second run will fail with EADDRINUSE while the old socket lingers in TIME_WAIT.
  • Using a port below 1024 outside a test environment. These privileged ports require root.

Summary

  • bind() claims a local (address, port) for a socket.
  • Set SO_REUSEADDR to avoid TIME_WAIT problems between runs.
  • Use INADDR_LOOPBACK to bind to localhost only.
  • Choose a high port (e.g. 8080) so you do not need root.

Practice with these exercises