]> git.itanic.dy.fi Git - BME280_driver/commitdiff
bmed: Avoid failing to bind() due to "Address already in use"
authorTimo Kokkonen <timo.t.kokkonen@iki.fi>
Wed, 10 Mar 2021 19:19:33 +0000 (21:19 +0200)
committerTimo Kokkonen <timo.t.kokkonen@iki.fi>
Thu, 11 Mar 2021 17:41:16 +0000 (19:41 +0200)
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 <timo.t.kokkonen@iki.fi>
bmed.c

diff --git a/bmed.c b/bmed.c
index 6970aa1bb7f31ba08a2b285c6f2e06e03a7583bb..31a60109c71a2b04c1c8f3b53a8e236aa8059fbd 100644 (file)
--- 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;