bool success = false;
for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
- if(!(aip->ai_family == AF_INET || aip->ai_family == AF_INET6)) {
+ /* Try to bind to TCP. */
+
+ int tcp_fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
+
+ if(tcp_fd == -1) {
continue;
}
- int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
+ int result = bind(tcp_fd, aip->ai_addr, aip->ai_addrlen);
+ closesocket(tcp_fd);
- if(fd == -1) {
+ if(result) {
+ if(errno == EADDRINUSE) {
+ /* If this port is in use for any address family, avoid it. */
+ success = false;
+ break;
+ } else {
+ continue;
+ }
+ }
+
+ /* If TCP worked, then we require that UDP works as well. */
+
+ int udp_fd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP);
+
+ if(udp_fd == -1) {
success = false;
break;
}
- int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
- closesocket(fd);
+ result = bind(udp_fd, aip->ai_addr, aip->ai_addrlen);
+ closesocket(udp_fd);
if(result) {
success = false;
break;
- } else {
- success = true;
}
+
+ success = true;
}
freeaddrinfo(ai);