Set the option after the socket has been successfully initialized. So, after:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
You can add (with standard C99 compound literal support):
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
Or:
const int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
Note than in addition to SO_REUSEADDR
, you might need to set SO_REUSEPORT
to get the desired behavior. This is done exactly the same way for both options.