title: UDP hole punching. Have server talk to client
body: <p>I been reading a lot on how to implement UDP hole punching but fore some reason I cannot make it work.</p>
  
  <p><strong>For those that are not familiar of what udp hole punching is here is my own definition:</strong></p>
  
  <p>The goal is to be able to transfer data between two clients (Client A
  and client B) with the help of a server. So client A connects to the server and sends its info. Client B does the same. The server has the nessesary info so that Client A is able to send data to Client B and vise versa . Therefore the server gives that info to both clients. Once both clients have that info about each other it is possible to start sending and receiving data between those clients without the help of the server.</p>
  
  <p>My goal is to be able to do what I just described (udp hole punching). <strong>Before doing so I think it will be helpful to be able to connect from the server to the client</strong>. In order to do so I plan to send the server the info about the client. Once the server receives that info attempt to connect to the client from scratch. Once I am able to perform that I should have everything I need to start implementing the real udp hole punching. </p>
  
  <p>Here is how I have things set up:</p>
  
  <p><img src="https://i.stack.imgur.com/VLB2X.png" alt="enter image description here"></p>
  
  <p>The top router has the server and bottom router connected to LAN ports. The bottom router (NAT) is connected to the top router via it's WAN port. And the client computer is connected to the bottom router to one of its LAN ports.</p>
  
  <p>So in that connection the client is able to see the server but the server is not able to see the client. </p>
  
  <p>So the algorithm I have done in pseudo code is:</p>
  
  <ul>
  <li>Client connects to server.</li>
  <li>Client send some UDP packages to the server in order to open some ports on the NAT</li>
  <li>Send information to the server on what ports the client is listening to.</li>
  <li>Once the server receives that info attempt to connect to the client from scratch. </li>
  </ul>
  
  <h2>Here is the implementation in code:</h2>
  
  <p><strong>Server:</strong></p>
  
  <pre><code>static void Main()
  {     
      /* Part 1 receive data from client */
      UdpClient listener = new UdpClient(11000);
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
      string received_data;
      byte[] receive_byte_array = listener.Receive(ref groupEP);       
      received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
  
      // get info
      var ip = groupEP.Address.ToString();
      var port = groupEP.Port;
  
      /* Part 2 atempt to connect to client from scratch */
      // now atempt to send data to client from scratch once we have the info       
      Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      IPEndPoint endPointClient = new IPEndPoint(IPAddress.Parse(ip), port);
      sendSocket.SendTo(Encoding.ASCII.GetBytes("Hello"), endPointClient);
  }
  </code></pre>
  
  <p><strong>Client:</strong></p>
  
  <pre><code>static void Main(string[] args)
  {
      /* Part 1 send info to server */
      Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,  ProtocolType.Udp);
      IPAddress send_to_address = IPAddress.Parse("192.168.0.132");
      IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 11000);
      sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
  
      // get info
      var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
  
      /* Part 2 receive data from server */
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
      byte[] buffer = new byte[1024];
      sending_socket.Receive(buffer);
  } 
  </code></pre>
  
  <p><strong>For some reason it worked a few times!</strong> It works when the client receives data successfully on the line: <code>sending_socket.Receive(buffer);</code></p>
  
  <p><strong>Things to note:</strong>
  If on the server on the second part I used the instance variable <code>listner</code> instead of creating the new variable <code>sendSocket</code> and send the bytes through that variable the client is able to receive the data being sent. Remember that the second part of the server is going to be implemented by a second client B that's why I am initializing variables again from scratch...</p>
  
  <hr>
  
  <h2>Edit:</h2>
  
  <p><strong>Here is a different way of looking at the same problem.</strong> When I initialize a new object instead of using the same object the client does not receives the response. </p>
  
  <p>I have a object of type UdpClient. I am able to send data with that object to the other peer. If I create another object of the same type with the same properties and attempt to send data it does not work! I might be missing to initialize some variables. I am able to set private variables with reflection so I should not have a problem. anyways here is the server code:</p>
  
  <pre><code>public static void Main()
  {
      // wait for client to send data
      UdpClient listener = new UdpClient(11000);
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);        
      byte[] receive_byte_array = listener.Receive(ref groupEP);
  
      // connect so that we are able to send data back
      listener.Connect(groupEP);
  
      byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
  
      // now let's atempt to reply back
  
      // this part does not work!
      UdpClient newClient = CopyUdpClient(listener, groupEP);
      newClient.Send(dataToSend, dataToSend.Length);
  
      // this part works!
      listener.Send(dataToSend, dataToSend.Length);
  }
  
  static UdpClient CopyUdpClient(UdpClient client, IPEndPoint groupEP)
  {
      var ip = groupEP.Address.ToString();
      var port = groupEP.Port;
      var newUdpClient = new UdpClient(ip, port);
      return newUdpClient;
  }
  </code></pre>
  
  <p>the client code basically sends data to the server and then waits for a response:</p>
  
  <pre><code>    string ipOfServer = "192.168.0.132";
      int portServerIsListeningOn = 11000;
  
      // send data to server
      Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      IPAddress send_to_address = IPAddress.Parse(ipOfServer);
      IPEndPoint sending_end_point = new IPEndPoint(send_to_address, portServerIsListeningOn);
      sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
  
      // get info
      var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
  
      // now wait for server to send data back
      IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
      byte[] buffer = new byte[1024];
      sending_socket.Receive(buffer); // &lt;----- keeps waiting in here :(
  </code></pre>
  
  <p><strong>note that the client is behind a router (NAT) otherwise I will not have this problem.</strong> The reason why I will like to copy udpClient is so that I can send that variable to another computer enabling the other computer to send data to the client. </p>
  
  <p><strong>So my question is</strong>  why is the original object <code>listener</code> able to send data but <code>newClient</code> is not able to? The client keeps waiting at line <code>sending_socket.Receive(buffer);</code> even after the server executes the line: <code>newClient.Send(dataToSend, dataToSend.Length);</code>. the client successfully receives data when listener sends the data but not newClient. Why is this if both variables have the same destination IP and port? how do the variables differ?</p>
  
  <p>Note:
  If the server and client are on the same network then the copy works and variable <code>newClient</code> is able to send data to the client. To simulate this problem the client must be behind a NAT (router). An example of such network may consist of two routers. let's call them router X and router Y. You also need a Server call that S. and a client C. so S can be connected to one of the LAN ports of X. C can be connected to one of the LAN ports of Y. Finally connect the WAN port of Y to one of the LAN ports of X.</p>