- /* Bind socket to address */
- if (bind(socket_fd, (struct sockaddr*) &server_addr,
- sizeof(server_addr)) < 0) {
- fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
+ /* Attempt binding of each address until success */
+ current_address = addresses;
+ while (current_address != NULL) {
+
+ /* Attempt to bind socket to address */
+ if (bind(socket_fd,
+ current_address->ai_addr,
+ current_address->ai_addrlen) == 0) {
+
+ /* Done if successful bind */
+ break;
+
+ }
+
+ /* Otherwise log error */
+ else
+ fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
+
+ current_address = current_address->ai_next;
+
+ }
+
+ /* If unable to bind to anything, fail */
+ if (current_address == NULL) {
+ fprintf(stderr, "Unable to bind socket to any addresses.\n");