Aggiornamenti + alcune sockopt di IP
[gapil.git] / listati / sockbind.c
1 int sockbind(char *host, char *serv, int prot, int type) 
2 {
3     struct addrinfo hint, *addr, *save;
4     int res;
5     int sock;
6     char buf[INET6_ADDRSTRLEN];
7     memset(&hint, 0, sizeof(struct addrinfo)); 
8     hint.ai_flags = AI_PASSIVE;            /* address for binding */
9     hint.ai_family = PF_UNSPEC;            /* generic address (IPv4 or IPv6) */
10     hint.ai_protocol = prot;               /* protocol */
11     hint.ai_socktype = type;               /* socket type */
12     res = getaddrinfo(host, serv, &hint, &addr);   /* calling getaddrinfo */
13     if (res != 0) {                                /* on error exit */
14         fprintf(stderr, "sockbind: resolution failed:");
15         fprintf(stderr, " %s\n", gai_strerror(res));
16         errno = 0;                         /* clear errno */
17         return -1;
18     }
19     save = addr;                           /* saving for freeaddrinfo */
20     while (addr != NULL) {                 /* loop on possible addresses */
21         sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
22         if (sock < 0) {                    /* on error */
23             if (addr->ai_next != NULL) {   /* if other addresses */
24                 addr=addr->ai_next;        /* take next */
25                 continue;                  /* restart cycle */
26             } else {                       /* else stop */
27                 perror("sockbind: cannot create socket");
28                 return sock;
29             }
30         }
31         if ( (res = bind(sock, addr->ai_addr, addr->ai_addrlen)) < 0) {
32             if (addr->ai_next != NULL) {   /* if other addresses */
33                 addr=addr->ai_next;        /* take next */
34                 close(sock);               /* close socket */
35                 continue;                  /* restart cycle */
36             } else {                       /* else stop */
37                 perror("sockbind: cannot connect");
38                 close(sock);
39                 return res;
40             }
41         } else break;                      /* ok, we are binded! */
42     }
43     freeaddrinfo(save);                    /* done, release memory */
44     return sock;
45 }