[PATCH 2/3] daemon: Set SO_REUSEADDR on listening sockets.
- From
- Mark Wooding <mdw@distorted.org.uk>
- Date
- Feb 3, 2006, 20:27 UTC
- Message-ID
- <20060203202704.1895.18383.stgit@metalzone.distorted.org.uk>
- In-Reply-To
- <20060203202330.1895.60474.stgit@metalzone.distorted.org.uk>
From: Mark Wooding <mdw@distorted.org.uk>
Without this, you can silently lose the ability to receive IPv4 connections if you stop and restart the daemon.
Signed-off-by: Mark Wooding <mdw@distorted.org.uk> ---
daemon.c | 14 ++++++++++++++ 1 files changed, 14 insertions(+), 0 deletions(-)
diff --git a/daemon.c b/daemon.c index 532bb0c..6b88c0c 100644 --- a/daemon.c +++ b/daemon.c @@ -454,6 +454,7 @@ static int socksetup(int port, int **soc int socknum = 0, *socklist = NULL; int maxfd = -1; char pbuf[NI_MAXSERV]; + int yes = 1; struct addrinfo hints, *ai0, *ai; int gai; @@ -491,6 +492,12 @@ static int socksetup(int port, int **soc } #endif + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, + &yes, sizeof(yes))) { + close(sockfd); + return 0; /* not fatal */ + } + if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) { close(sockfd); continue; /* not fatal */ @@ -523,6 +530,7 @@ static int socksetup(int port, int **soc { struct sockaddr_in sin; int sockfd; + int yes = 1; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) @@ -533,6 +541,12 @@ static int socksetup(int port, int **soc sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(port); + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, + &yes, sizeof(yes))) { + close(sockfd); + return 0; + } + if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) { close(sockfd); return 0;