Search code examples
c++networkingtcpwinsock2

How do you create a TCP connection without a listener?


I am currently working on a C++ networking program using Winsock 2, it's a chatting program without a server between the two computers. It would be convenient if none of the users are forced to run a server program, which has a listener, it makes them have to port forward. This would, of course, require them to both enter each other's IPs, but that's okay. Is there a way to create a TCP connection by running the same client program on two different computers, using the same port and each inputting the other computer's IP without having to port forward?


Solution

  • Although you will need to call bind in order to allow another machine to connect to that port, you do not need to call accept.

    As long as both processes have called bind on their accepting port, then assuming that the address sin is initialized to the appropriate destination, each process can symmetrically connect to each other using a loop that looks like this:

      while (connect(s, sin, slen) < 0) {
          if (errno == ECONNREFUSED) continue;
          perror("connect");
          _exit(0);
      }
    

    This is the "simultaneous open" case in the TCP state machine diagram. Each side sends SYN simultaneously, so each side responds with SYN/ACK. After each side sends ACK to complete the 3-way handshake, both sides enter the ESTABLISHED state.

    Try It Online does not support threads or access to loopback, but it does allow me to conveniently present the complete coding example.