From bee2413bba67bdd144d7844d2dd8b34d444e8ac0 Mon Sep 17 00:00:00 2001 From: Timo Kokkonen Date: Wed, 10 Mar 2021 21:19:33 +0200 Subject: [PATCH] bmed: Avoid failing to bind() due to "Address already in use" If the previous invocation of the process happened just a while ago (eg. the daemon was restarted), the listening socket might still be in TIME_WAIT state, which prevents registering a new listening socket to the port. This can be avoided by using the SO_REUSEADDR option which instructs bind() call to bind to the port anyway. Signed-off-by: Timo Kokkonen --- bmed.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bmed.c b/bmed.c index 6970aa1..31a6010 100644 --- a/bmed.c +++ b/bmed.c @@ -246,6 +246,7 @@ static void *event_handler(void *arg) struct sockaddr_in addr; struct listening_socket incoming; int sockfd, ret; + int enable = 1; bzero(&addr, sizeof(addr)); bzero(&incoming, sizeof(incoming)); @@ -256,6 +257,10 @@ static void *event_handler(void *arg) goto out; } + ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)); + if (ret < 0) + printf("Error setting SO_REUSEADDR: %m\n"); + addr.sin_family = AF_INET; addr.sin_port = htons(8347); addr.sin_addr.s_addr = INADDR_ANY; -- 2.45.0