C++ Winsock P2P

If you just want to implement a P2P application on Microsoft Windows, you can try with Windows Peer-to-Peer Networking

If you want to implement a new P2P protocol of your own, you can study the eMule protocol, and eMule source code. You could do further if you look into Shareaza source code, it do eMule/Guntella/Gnutella/BitTorrent.


Since I don't know what information you are looking for, I'll try to describe how to set up a socket program and what pitfalls I've run into.

To start with, *read the Winsock tutorial at MSDN. This is a basic program to connect, send a message and disconnect. It's great for getting a feel for socket programming.

With that, lets start:

Considerations:

  • Blocking or non-blocking

    First off, you need to decide whether you want a blocking or non-blocking program. If you have a GUI you would need to use non-blocking or threading in order to not freeze the program. The way I did it was to use the blocking calls, but always calling select before calling the blocking functions (more on select later). This way I avoid threading and mutex's and whatnot but still use the basic accept, send and receive calls.

  • You cannot rely that your packets will arrive the way you send them!

    You have no control over this either. This was the biggest issue I ran into, basically because the network card can decide what information to send and when to send it. The way I solved it was to make a networkPackageStruct, containing a size and data, where size is the total amound of data in that packet. Note that a message that you send can be split into 2 or more packets and can also be merged with another message you send.

    Consider the following:

    You send two messages

      "Hello"
      "World!"
    

    When you send these two messages with the send function your recv function might not get them like this. It could look like this:

      "Hel"
      "loWorld!"
    

    or perhaps

      "HelloWorld!"
    

    whatever the underlying network feels like.

  • Log (almost) everything!

    Debugging a network program is hard because you don't have full control over it (since it's on two computers). If you run into a blocking operation you can't see it either. This could as well be called "Know your blocking code". When one side sends something, you don't know if it will arrive on the other side, so keep track of what is sent and what is received.

  • Pay attention to socket errors

    Winsock functions return a lot of information. Know your WSAGetLastError() function. I'll won't keep it in the examples below, but note that they tend to return alot of information. Every time you get a SOCKET_ERROR or INVALID_SOCKET check the Winsock Error Messages to look it up.

Setting up the connection:

  • Since you don't want a server, all clients would need a listening socket to accept new connections. The easiest is:

      SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      sockaddr_in localAddress;
      localAddress.sinfamily = AF_INET;
      localAddress.sin_port = htons(10000);  // or whatever port you'd like to listen to
      localAddress.sin_addr.s_addr = INADDR_ANY;
    

    INADDR_ANY is great - it makes your socket listen on all your IP addresses instead of just one IP address.

      bind(s, (SOCKADDR*)&localAddress, sizeof(localAddress));
      listen(s, SOMAXCONN);
    

    Here comes the interesting part. bind and listen won't block but accept will. The trick is to use select to check if there is an incoming connection. So the above code is just to set the socket up. in your program loop you check for new data in socket.

Exchanging data

  • The way I solved it is was to use select alot. Basically you see if there are anything you need to respond to on any of your sockets. This is done with the FD_xxx functions.

      // receiving data
      fd_set mySet;
      FD_ZERO(&mySet);
      FD_SET(s, &mySet);
      // loop all your sockets and add to the mySet like the call above
      timeval zero = { 0, 0 };
      int sel = select(0, &mySet, NULL, NULL, &zero);
      if (FD_ISSET(s, &mySet)){
          // you have a new caller
          sockaddr_in remote;
          SOCKET newSocket = accept(s, (SOCKADDR*)&remote, sizeof(remote));
      }
      // loop through your sockets and check if they have the FD_ISSET() set
    

In the newSocket you now have a new peer. So that was for receiving data. But note! send is also blocking! One of the head-scratching errors I got was that send blocked me. This was however also solved with select.

 // sending data
 // in: SOCKET sender
 fd_set mySet;
 FD_ZERO(&mySet);
 FD_SET(sender, &mySet);
 timeval zero = { 0, 0 };
 int sel = select(0, NULL, mySet, NULL, &zero);
 if (FD_ISSET(sender, &mySet)){
      // ok to send data
 }

Shutting down

Finally, there are two ways to shutdown. You either just disconnect by closing your program, or you call the shutdown function.

  • Calling shutdown will make your peer select trigger. recv will however not receive any data, but will instead return 0. I have not noticed any other case where recv returns 0, so it is (somewhat) safe to say that this can be considered a shutdown-code. calling shutdown is the nicest thing to do.
  • Shutting down the connection without calling shutdown just is cold-hearted, but of course works. You still need to handle the error even if you use shutdown, since it might not be your program that closes the connection. A good error code to remember is 10054 which is WSAECONNRESET: Connection reset by peer.