#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
+#include <netdb.h>
+#include <string.h>
+#include <stdio.h>
#include <errno.h>
int sockconn(char *host, char *serv, int prot, int type)
{
- struct addrinfo hint, *addr;
+ struct addrinfo hint, *addr, *save;
int res;
- int sock
- /* initialize hint */
- memset(&hint, 0, sizeof(hint));
- hint.ai_family = PF_UNSPEC;
- hint.ai_protocol = prot;
- hint.ai_socktype = type;
- res = getaddrinfo(host, serv, &hint, &addr);
- if (res != 0) {
- printf("sockconn cannot resolve host %s, service %s,
- protocol %d: %s\n", host, serv, prot, gai_strerror(res));
- errno = 0;
+ int sock;
+ /* initialize hint structure */
+ memset(&hint, 0, sizeof(struct addrinfo));
+ 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 */
+ printf("sockconn cannot resolve host %s, service %s, ", host, serv);
+ printf("protocol %d: %s\n", prot, gai_strerror(res));
+ errno = 0; /* clear errno */
return -1;
}
- sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
- if (sock < 0) {
- perror("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) {
+ if (addr->ai_next == NULL) {
+ addr=addr->ai_next;
+ continue;
+ } else {
+ printf("sockconn cannot create socket\n");
+ return sock;
+ }
+ }
+ /* connect the socket */
+ res = connect(sock, addr->ai_addr, addr->ai_addrlen);
+ if (res < 0) {
+ if (addr->ai_next == NULL) {
+ close(sock);
+ addr=addr->ai_next;
+ continue;
+ } else {
+ printf("sockconn cannot connect socket\n");
+ return res;
+ }
+ }
}
- res = connect(sock, addr->ai_addr, addr->ai_addrlen);
- if (res < 0) {
- perror("sockconn cannot connect socket\n");
- return res;
- }
- freeaddrinfo(addr);
+ freeaddrinfo(save); /* done, release memory */
return sock;
}
-