X-Git-Url: https://gapil.gnulinux.it/gitweb/?p=gapil.git;a=blobdiff_plain;f=sources%2FSockUtil.c;h=a2a6fcdb295665a0828db434656c3bbf2e20e812;hp=0bbaa79605fec851784e93ca729ccf1825f746e9;hb=1bc54870307368cc8c74e07f7f4dd53498e09db0;hpb=866f3cf8f2fe10ea9c7b5c4b10faf37fce74b1aa diff --git a/sources/SockUtil.c b/sources/SockUtil.c index 0bbaa79..a2a6fcd 100644 --- a/sources/SockUtil.c +++ b/sources/SockUtil.c @@ -193,3 +193,70 @@ int sockbind(char *host, char *serv, int prot, int type) freeaddrinfo(save); /* done, release memory */ return sock; } +/**************************************************************** + * + * Routine sockbindopt + * Return a binded socket given hostname, service, and socket type + * Issue a SO_REUSEADDR on the socket before binding on reuse value. + * + * Author: Simone Piccardi + * Mar. 2005 + * + * $Id$ + * + ****************************************************************/ +int sockbindopt(char *host, char *serv, int prot, int type, int reuse) +{ + struct addrinfo hint, *addr, *save; + int res; + int sock; + char buf[INET6_ADDRSTRLEN]; + /* initialize hint structure */ + memset(&hint, 0, sizeof(struct addrinfo)); + hint.ai_flags = AI_PASSIVE; /* address for binding */ + hint.ai_family = PF_UNSPEC; /* generic address (IPv4 or IPv6) */ + hint.ai_protocol = prot; /* protocol */ + hint.ai_socktype = type; /* socket type */ + res = getaddrinfo(host, serv, &hint, &addr); /* calling getaddrinfo */ + if (res != 0) { /* on error exit */ + fprintf(stderr, "sockbind: resolution failed:"); +// fprintf(stderr, "host %s, service %s, protocol %d", host, serv, prot); + fprintf(stderr, " %s\n", gai_strerror(res)); + errno = 0; /* clear errno */ + return -1; + } + save = addr; /* saving for freeaddrinfo */ + while (addr != NULL) { /* loop on possible addresses */ + /* get a socket */ + sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); + if (sock < 0) { /* on error */ + if (addr->ai_next != NULL) { /* if other addresses */ + addr=addr->ai_next; /* take next */ + continue; /* restart cycle */ + } else { /* else stop */ + perror("sockbind: cannot create socket"); + return sock; + } + } + /* connect the socket */ + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + &reuse, sizeof(reuse))) { + printf("error on socket options\n"); + return -1; + } + printf("Indirizzo %s\n", ip_ntop(addr, buf, sizeof(buf))); + if ( (res = bind(sock, addr->ai_addr, addr->ai_addrlen)) < 0) { + if (addr->ai_next != NULL) { /* if other addresses */ + addr=addr->ai_next; /* take next */ + close(sock); /* close socket */ + continue; /* restart cycle */ + } else { /* else stop */ + perror("sockbind: cannot connect"); + close(sock); + return res; + } + } else break; /* ok, we are binded! */ + } + freeaddrinfo(save); /* done, release memory */ + return sock; +}