X-Git-Url: https://gapil.gnulinux.it/gitweb/?p=gapil.git;a=blobdiff_plain;f=sources%2Fsockbind.c;h=4ecbe97962ac8a8c6cd41f6fdf69a73652da944a;hp=3e31fe7e9c4998880793828ea0c20a63e450a51e;hb=f56df9c083fb4cfcfc410513304be39602001ae7;hpb=8654ce33b450ae7bb34c3907835000a0760c2931 diff --git a/sources/sockbind.c b/sources/sockbind.c index 3e31fe7..4ecbe97 100644 --- a/sources/sockbind.c +++ b/sources/sockbind.c @@ -37,7 +37,7 @@ int sockbind(char *host, char *serv, int prot, int type) { - struct addrinfo hint, *addr; + struct addrinfo hint, *addr, *save; int res; int sock; /* initialize hint structure */ @@ -50,20 +50,26 @@ int sockbind(char *host, char *serv, int prot, int type) if (res != 0) { /* on error exit */ printf("sockbind cannot resolve host %s, service %s, ", host, serv); printf("protocol %d: %s\n", prot, gai_strerror(res)); + errno = 0; /* clear errno */ return -1; } - /* get a socket */ - sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); - if (sock < 0) { - printf("sockconn cannot create socket\n"); - return sock; + /* loop on possible addresses */ + save = addr; + while (addr != NULL) { + /* get a socket */ + sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); + if ( (sock < 0) && (addr->ai_next == NULL) ) { + printf("sockbind cannot create socket\n"); + return sock; + } else continue; + /* connect the socket */ + res = bind(sock, addr->ai_addr, addr->ai_addrlen); + if ( (res < 0) && (addr->ai_next == NULL) ) { + printf("sockbind cannot bind socket\n"); + return res; + } + addr=addr->ai_next; } - /* connect the socket */ - res = bind(sock, addr->ai_addr, addr->ai_addrlen); - if (res < 0) { - printf("sockconn cannot bind socket\n"); - return res; - } - freeaddrinfo(addr); /* done, release memory */ + freeaddrinfo(save); /* done, release memory */ return sock; }