From: Guus Sliepen Date: Tue, 25 Feb 2020 19:39:48 +0000 (+0100) Subject: Fix logic in try_bind(). X-Git-Url: https://git.meshlink.io/?a=commitdiff_plain;h=b5aaabe0fcb104ef7801a68f4f9e6b77732dbb28;p=meshlink Fix logic in try_bind(). Fix the check for successful socket creation. Also make sure we only return success if we can bind to IPv4 and IPv6, but ignore other network protocols. --- diff --git a/src/meshlink.c b/src/meshlink.c index fbacfd4a..6fd89dad 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -537,26 +537,33 @@ static bool try_bind(int port) { return false; } - //while(ai) { + bool success = false; + for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) { + if(!(aip->ai_family == AF_INET || aip->ai_family == AF_INET6)) { + continue; + } + int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP); - if(!fd) { - freeaddrinfo(ai); - return false; + if(fd == -1) { + success = false; + break; } int result = bind(fd, aip->ai_addr, aip->ai_addrlen); closesocket(fd); if(result) { - freeaddrinfo(ai); - return false; + success = false; + break; + } else { + success = true; } } freeaddrinfo(ai); - return true; + return success; } static int check_port(meshlink_handle_t *mesh) {