C++ Winsock P2P

C++ Winsock P2P

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.

p2p communication using winsock

Where are you getting server_name from? Are you sure it's a valid IP address?
Also, check WSAGetLastError() to see specifically what's going wrong.

Remember that not all hostnames have reverse DNS entries. It's perfectly legitimate for gethostbyaddr to fail on a real, valid IP address. If you're doing p2p, it's best not to rely on host names at all, except perhaps for diagnostic displays (and fall back to IP addresses if reverse lookups fail).

Edit: With your new, expanded code sample, it's clear that you actually don't need gethostbyaddr at all.

struct sockaddr_in server;
memset((void*)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.S_un.S_long = inet_addr(server_name);
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0);

connect(conn_socket, (struct sockaddr*)&server, sizeof(server))

gethostbyaddr is only needed when you need the reverse DNS name of the server in question. inet_addr already gives you a suitable address to connect to.

Is there a P2P framework in c?

Chimera is the successor to Tapestry, one of the original 4 P2P overlay networks (along with CAN, Pastry, and Chord). It's written in C: http://current.cs.ucsb.edu/projects/chimera/

Note that this is a base-level overlay network that you can build other stuff on top of (like messaging or file sharing).

Socket program Python vs C++ (Winsock)

Per the docs, sendto returns a number that's >0 (number of bytes sent) for success, <0 for failure, and in the latter case you use WSAGetLastError for more information. So try saving the sendto result, printing it (as well as the size of the data you're trying to send), and in case of error print the last-error code too. What do you see then?



Related Topics



Leave a reply



Submit