UDP hole punching implementation

If i understand correctly, you are trying to communicate peer-to-peer between 2 clients each behind a different NAT, using a mediation server for hole punching?

Few years ago i did the exact same thing in c#, i haven’t found the code yet, but ill give you some pointers if you like:

First, I wouldn’t use the Connect() function on the udpclient, since UDP is a connectionless protocol, all this function really does is hide the functionality of a UDP socket.

You should perfrom the following steps:

  1. Open a UDP socket on a server with it’s ports not blocked by a firewall, at a specific port (eg Bind this socket to a chosen port for example 23000)
  2. Create a UDP socket on the first client, and send something to the server at 23000. Do not bind this socket. When a udp is used to send a packet, windows will automatically assign a free port to the socket
  3. Do the same from the other client
  4. The server has now received 2 packets from 2 clients at 2 different adresses with 2 different ports. Test if the server can send packets back on the same address and port. (If this doesn’t work you did something wrong or your NAT isn’t working. You know its working if you can play games without opening ports :D)
  5. The server should now send the address and port of the other clients to each connected client.
  6. A client should now be able to send packets using UDP to the adresses received from the server.

You should note that the port used on the nat is probably not the same port as on your client pc!! The server should distribute this external port to clients. You must use the external adresses and the external ports to send to!

Also note that your NAT might not support this kind of port forwarding. Some NAT’s forward all incoming traffic on a assigned port to you client, which is what you want. But some nats do filtering on the incoming packets adresses so it might block the other clients packets. This is unlikely though when using a standard personal user router.

Leave a Comment