Networking in C · beginner · ~8 min
Bind a server socket to a local address and port.
bind() doesThe 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.
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.
#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;
}
SO_REUSEADDR. Your second run will fail with EADDRINUSE while the old socket lingers in TIME_WAIT.bind() claims a local (address, port) for a socket.SO_REUSEADDR to avoid TIME_WAIT problems between runs.INADDR_LOOPBACK to bind to localhost only.