- /* 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;
+ save = addr; /* saving for freeaddrinfo */
+ while (addr != NULL) { /* loop on possible addresses */
+ sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
+ if (sock < 0) { /* on error */
+ if (addr->ai_next != NULL) { /* if other addresses */
+ addr=addr->ai_next; /* take next */
+ continue; /* restart cycle */
+ } else { /* else stop */
+ perror("sockbind: cannot create socket");
+ return sock;
+ }
+ }
+ if ( (res = bind(sock, addr->ai_addr, addr->ai_addrlen)) < 0) {
+ if (addr->ai_next != NULL) { /* if other addresses */
+ addr=addr->ai_next; /* take next */
+ close(sock); /* close socket */
+ continue; /* restart cycle */
+ } else { /* else stop */
+ perror("sockbind: cannot connect");
+ close(sock);
+ return res;
+ }
+ } else break; /* ok, we are binded! */