From 1ab9403c5eb08bcb47e8e1599764b5465c79795b Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Fri, 28 Feb 2020 19:25:52 +0100 Subject: [PATCH] Further improve try_bind(). Make try_bind() do the same checks as add_listen_address() does: try to create both a TCP and UDP socket on a given port for all address families. If one address family succeeds for both TCP and UDP, consider this a valid port. --- src/meshlink.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/meshlink.c b/src/meshlink.c index 6fd89dad..4e32761f 100644 --- a/src/meshlink.c +++ b/src/meshlink.c @@ -540,25 +540,33 @@ static bool try_bind(int port) { bool success = false; for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) { - if(!(aip->ai_family == AF_INET || aip->ai_family == AF_INET6)) { + 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) { - success = false; - break; + if(result) { + continue; } - int result = bind(fd, aip->ai_addr, aip->ai_addrlen); - closesocket(fd); + int udp_fd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP); + + if(udp_fd == -1) { + continue; + } + + result = bind(udp_fd, aip->ai_addr, aip->ai_addrlen); + closesocket(udp_fd); if(result) { - success = false; - break; + continue; } else { success = true; + break; } } -- 2.39.5