Skip to content

setsockopt()

Purpose

setsockopt() configures socket options.

It is commonly used to enable SO_REUSEADDR for local server testing.

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

Prototype

int setsockopt(int sockfd, int level, int optname,
               const void *optval, socklen_t optlen);

Minimal Example

int enable = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
               &enable, sizeof(enable)) < 0) {
    perror("setsockopt");
    return -1;
}

Common Pitfalls

  • Passing the wrong level, such as SOL_SOCKET vs IPPROTO_TCP.
  • Passing the wrong option value size.
  • Expecting SO_REUSEADDR to solve all bind conflicts.