socket: use listen() and SO_REUSEADDR, new osmo_sock_init_ofd() function
authorHarald Welte <laforge@gnumonks.org>
Sun, 22 May 2011 19:47:29 +0000 (21:47 +0200)
committerHarald Welte <laforge@gnumonks.org>
Sun, 22 May 2011 19:47:29 +0000 (21:47 +0200)
osmo_sock_init_ofd() is a wrapper around osmo_sock_init() which will
take care of initializing and registering a 'struct osmo_fd' for the
newly-created socket.

include/osmocom/core/socket.h
src/socket.c

index a3baa9d..b2601c7 100644 (file)
@@ -8,6 +8,9 @@ struct sockaddr;
 int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
                   const char *host, uint16_t port, int connect0_bind1);
 
+int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
+                       const char *host, uint16_t port, int connect0_bind1);
+
 int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
                      uint8_t proto, int connect0_bind1);
 
index 2414b1f..66907c8 100644 (file)
@@ -23,7 +23,7 @@ int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
                   const char *host, uint16_t port, int connect0_bind1)
 {
        struct addrinfo hints, *result, *rp;
-       int sfd, rc;
+       int sfd, rc, on = 1;
        char portbuf[16];
 
        sprintf(portbuf, "%u", port);
@@ -58,6 +58,39 @@ int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
                perror("unable to connect/bind socket");
                return -ENODEV;
        }
+
+       setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
+
+       /* Make sure to call 'listen' on a bound, connection-oriented sock */
+       if (connect0_bind1 == 1) {
+               switch (type) {
+               case SOCK_STREAM:
+               case SOCK_SEQPACKET:
+                       listen(sfd, 10);
+                       break;
+               }
+       }
+       return sfd;
+}
+
+int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
+                       const char *host, uint16_t port, int connect0_bind1)
+{
+       int sfd, rc;
+
+       sfd = osmo_sock_init(family, type, proto, host, port, connect0_bind1);
+       if (sfd < 0)
+               return sfd;
+
+       ofd->fd = sfd;
+       ofd->when = BSC_FD_READ;
+
+       rc = osmo_fd_register(ofd);
+       if (rc < 0) {
+               close(sfd);
+               return rc;
+       }
+
        return sfd;
 }