ddf48d8962c7a4b4b286bb92e611f5b9a0c3570b
[gapil.git] / listati / sockbind.c
1 int sockbind(char *host, char *serv, int prot, int type) 
2 {
3     struct addrinfo hint, *addr;
4     int res;
5     int sock;
6     /* initialize hint structure */
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         printf("sockbind cannot resolve host %s, service %s, ", host, serv);
15         printf("protocol %d: %s\n", prot, gai_strerror(res));
16         return -1;
17     }
18     /* get a socket */
19     sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
20     if (sock < 0) {
21         printf("sockconn cannot create socket\n");
22         return sock;
23     }
24     /* connect the socket */
25     res = bind(sock, addr->ai_addr, addr->ai_addrlen);
26     if (res < 0) {
27         printf("sockconn cannot bind socket\n");
28         return res;
29     }
30     freeaddrinfo(addr);         /* done, release memory */
31     return sock;
32 }