Search code examples
csocketswinapilibevent

3 sockets created for one libevent bind on Windows?


I'm writing a BitTorrent client to learn some more about networking, and I've got something that I'm struggling to Google for. As part of the BT spec, I need a server to listen for peer connections to my computer. In the win32 port, I have code like this to setup my server

struct sockaddr_in saServer;
struct hostent* localHost;
char* localIP;

// Get the local host information
localHost = gethostbyname("");
localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);

saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = inet_addr(localIP);
saServer.sin_port = htons(6881);


struct evconnlistener *listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
    LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, (SOCKADDR*)&saServer, sizeof(saServer));

That seems to work, but if I look at netstat, I see the following,

BitTorrentClient.exe    6092    TCP hostname    50216   localhost   50217   ESTABLISHED                                     
BitTorrentClient.exe    6092    TCP hostname    50217   localhost   50216   ESTABLISHED                                     
BitTorrentClient.exe    6092    TCP hostname.home 6881  hostname    0   LISTENING   

Why are there two other connections, one from port 50216->50217 and one looping back from 50217->50216? I was expected to have just one listening connection on port 6881. Is this a libevent quirk, or something more fundamental related to networking?

What can I search for to understand what the other two ports are used for?


Solution

  • This is most likely a result of libevent calling evutil_make_internal_pipe_ internally.

    Libevent creates internal "pipes" for inter-thread communication and signal delivery using socketpair(2) on POSIX-compliant systems, whereas on Windows libevent has to resort to manually connecting two sockets together instead.