1 int sockconn(char *host, char *serv, int prot, int type)
3 struct addrinfo hint, *addr, *save;
6 memset(&hint, 0, sizeof(struct addrinfo));
7 hint.ai_family = PF_UNSPEC; /* generic address (IPv4 or IPv6) */
8 hint.ai_protocol = prot; /* protocol */
9 hint.ai_socktype = type; /* socket type */
10 res = getaddrinfo(host, serv, &hint, &addr); /* calling getaddrinfo */
11 if (res != 0) { /* on error exit */
12 fprintf(stderr, "sockconn: resolution failed:");
13 fprintf(stderr, " %s\n", gai_strerror(res));
14 errno = 0; /* clear errno */
18 while (addr != NULL) { /* loop on possible addresses */
19 sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
20 if (sock < 0) { /* on error */
21 if (addr->ai_next != NULL) { /* if other addresses */
22 addr=addr->ai_next; /* take next */
23 continue; /* restart cycle */
24 } else { /* else stop */
25 perror("sockconn: cannot create socket");
29 if ( (res = connect(sock, addr->ai_addr, addr->ai_addrlen) < 0)) {
30 if (addr->ai_next != NULL) { /* if other addresses */
31 addr=addr->ai_next; /* take next */
32 close(sock); /* close socket */
33 continue; /* restart cycle */
34 } else { /* else stop */
35 perror("sockconn: cannot connect");
39 } else break; /* ok, we are connected! */
41 freeaddrinfo(save); /* done, release memory */