diff --git a/src/dht.cpp b/src/dht.cpp index d5305fd9..ee74d39b 100644 --- a/src/dht.cpp +++ b/src/dht.cpp @@ -29,51 +29,10 @@ extern "C" { #include } -#ifndef _WIN32 -#include -#else -#include -#endif - #include #include #include -#ifndef _WIN32 -#include -#else -#include -#endif - -#include -#include - -#ifdef _WIN32 - -static bool -set_nonblocking(int fd, int nonblocking) -{ - unsigned long mode = !!nonblocking; - int rc = ioctlsocket(fd, FIONBIO, &mode); - return rc == 0; -} - -extern const char *inet_ntop(int, const void *, char *, socklen_t); - -#else - -static bool -set_nonblocking(int fd, int nonblocking) -{ - int rc = fcntl(fd, F_GETFL, 0); - if (rc < 0) - return false; - rc = fcntl(fd, F_SETFL, nonblocking?(rc | O_NONBLOCK):(rc & ~O_NONBLOCK)); - return rc >= 0; -} - -#endif - namespace dht { using namespace std::placeholders; @@ -1841,18 +1800,10 @@ Dht::Dht(int s, int s6, Config config) scheduler.syncTime(); if (s < 0 && s6 < 0) return; - - if (s >= 0) { + if (s >= 0) buckets4 = {Bucket {AF_INET}}; - if (!set_nonblocking(s, 1)) - throw DhtException("Can't set socket to non-blocking mode"); - } - - if (s6 >= 0) { + if (s6 >= 0) buckets6 = {Bucket {AF_INET6}}; - if (!set_nonblocking(s6, 1)) - throw DhtException("Can't set socket to non-blocking mode"); - } search_id = std::uniform_int_distribution{}(rd); diff --git a/src/network_engine.cpp b/src/network_engine.cpp index f4b22a7a..56b821f2 100644 --- a/src/network_engine.cpp +++ b/src/network_engine.cpp @@ -25,6 +25,17 @@ #include +#ifndef _WIN32 +#include +#include +#else +#include +#include +#endif +#include + +#include + namespace dht { namespace net { @@ -58,6 +69,32 @@ static const uint8_t v4prefix[16] = { constexpr unsigned SEND_NODES {8}; +#ifdef _WIN32 + +static bool +set_nonblocking(int fd, int nonblocking) +{ + unsigned long mode = !!nonblocking; + int rc = ioctlsocket(fd, FIONBIO, &mode); + return rc == 0; +} + +extern const char *inet_ntop(int, const void *, char *, socklen_t); + +#else + +static bool +set_nonblocking(int fd, int nonblocking) +{ + int rc = fcntl(fd, F_GETFL, 0); + if (rc < 0) + return false; + rc = fcntl(fd, F_SETFL, nonblocking?(rc | O_NONBLOCK):(rc & ~O_NONBLOCK)); + return rc >= 0; +} + +#endif + enum class MessageType { Error = 0, Reply, @@ -151,6 +188,14 @@ NetworkEngine::NetworkEngine(InfoHash& myid, NetId net, int s, int s6, Logger& l onGetValues(onGetValues), onListen(onListen), onAnnounce(onAnnounce), onRefresh(onRefresh), myid(myid), network(net), dht_socket(s), dht_socket6(s6), DHT_LOG(log), scheduler(scheduler) { + if (dht_socket >= 0) { + if (!set_nonblocking(dht_socket, 1)) + throw DhtException("Can't set socket to non-blocking mode"); + } + if (dht_socket6 >= 0) { + if (!set_nonblocking(dht_socket6, 1)) + throw DhtException("Can't set socket to non-blocking mode"); + } transaction_id = std::uniform_int_distribution{1}(rd_device); }