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);
| Argument | Values | Meaning |
|---|---|---|
domain | AF_INET, AF_INET6, AF_UNIX | Address family the socket will use |
type | SOCK_STREAM, SOCK_DGRAM, SOCK_RAW | Stream (TCP), datagram (UDP), raw |
protocol | 0 | Pick 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
| errno | Cause | Fix |
|---|---|---|
EADDRINUSE | Port busy or in TIME_WAIT | SO_REUSEADDR, or find the other process |
EACCES | Port below 1024 without privileges | Use a higher port, or grant CAP_NET_BIND_SERVICE |
EADDRNOTAVAIL | The IP address isn’t on this machine | Bind to the wildcard or an address the host owns |
EINVAL | Socket already bound | Bind only once |
Key takeaways
socket()returns an unbound descriptor; take its arguments fromgetaddrinfo().- Servers bind to a known port; clients let
connect()bind implicitly. - Set
SO_REUSEADDRbeforebind()on every TCP server so restarts don’t fail. - Bind to port 0 for “any free port” and read the result with
getsockname().
Exercises
- Write a server skeleton without
SO_REUSEADDR, reproduce theEADDRINUSEerror after a restart, then add the option and confirm it’s gone. - Bind to port 0 three times in one program and print the three ports chosen.
- Try to bind to port 80 as a normal user and print
strerror(errno).
Quiz
- Why does a typical TCP client not call
bind()? - What problem does
SO_REUSEADDRsolve? - How do you find which port the kernel picked after binding to port 0?
Show answers
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.- 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”.
- Call
getsockname()on the socket and read the port (withntohs()).