TCP hole punching using StreamingSocket

Hello, im trying to use TCP hole punching to establish a p2p connection to transfer audio files without a server, and I feel like I’m close, but no cigar… both the clients are connecting to my server and receiving each others public ip/port and local port. Server code from here:

Next, I am attempting to have both connect using the each others IPs and ports but this is causing the connection to fail. To test this im trying to send a string and see if I can receive it. I know the addresses I get from the server are correct.

Am I misimplementing this algorithm? I’m having a hard time with this. I’ve noticed that in the client code of the linked server i posted (here) they bind to the local port of the opposite client, if it I attempt to BindPort(…) after creating a socket I get a result of -1 due to an invalid handle.

Bit lost, could anyone kindly point me in the right direction?

Client A

            m_poConnectSocket->bindToPort(strTokens[4].getIntValue()); // local port
            if (m_poConnectSocket->connect(m_StrYourIp, m_StrYourPort.getIntValue()))
            {
                bSuccessDirect = true;
                for (int i = 0; i < 5; i++)
                {
                    String strSize = "test";
                    int iBytesWritten = m_poConnectSocket->write(strSize.getCharPointer(), strSize.getNumBytesAsUTF8());
                    String bytes(iBytesWritten);
                    DBG(bytes);
                    Sleep(3000);
                }
            }
            else
            {
                DBG("Failed to connect");
            }

Client B

StreamingSocket* poListener = new StreamingSocket;
			poListener->connect(strYourIp, strYourPort.getIntValue());
			if (poListener != nullptr)
			{
				printf("\nConnected!");
				printf("Bound port %d\n", poListener->getBoundPort());

				int iDataRead = 0;
				while (true)
				{
					if (poListener != nullptr &&
						poListener->isConnected())
					{
						iDataRead = poListener->read(poBuffer, MAX_BUFFER_SIZE - 1, false);
						if (iDataRead > 0)
						{
							bool test = false;
							printf("data received: %d\n", iDataRead);
						}
					}
					else
					{
						bool bProblem = true;
					}
				}
				String strRead1(CharPointer_UTF8(poBuffer), iDataRead);
				printf(strRead1.getCharPointer());
				bool test = false;
			}
1 Like

I’ve had several attempts at hole punching but never managed to get it to work, so can’t offer any advice, but interested to see if anyone comes up with anything.