Networking in C · beginner · ~8 min

bind() — claim a local port

Bind a server socket to a local address and port.

Lesson

bind(fd, &addr, sizeof addr) tells the kernel: "this socket is the one that owns port N on address A." After a successful bind, packets to that (addr, port) get routed to this fd.

Common errors:

  • EADDRINUSE — another process is already bound to that port (or your previous run left a TIME_WAIT socket around). Set SO_REUSEADDR to allow rebinding immediately:
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);
  • EACCES — ports below 1024 require root. Pick a high port (e.g. 8080) for your labs.

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.
  • Picking a port below 1024 outside of a test environment.

Summary

bind() claims a local (addr, port). Set SO_REUSEADDR to avoid TIME_WAIT pain. Use INADDR_LOOPBACK for localhost-only.

Practice with these exercises