title: How do I do TCP hole punching?
body: <p>Question is below. Here is my current test code which did not succeed.</p>
  
  <pre><code>static void Main(string[] args)
  {
      if (args.Count() != 3)
      {
          Console.WriteLine("Bad args");
      }
      var ep = new IPEndPoint(IPAddress.Parse(args[0]), int.Parse(args[1]));
      var lp = new IPEndPoint(IPAddress.Any, int.Parse(args[2]));
  
      var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
      s.Bind(lp);
  
      var c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      c.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
      c.Bind(lp);
  
      Task.Run(() =&gt; { try { c.Connect(ep); } catch { } });
      s.Listen(10);
      var v = s.Accept();
      v.Close();
  }
  </code></pre>
  
  <hr>
  
  <p>How do I do TCP hole punching? I am testing using a remote server. I'm running <code>wget local_public_ip:port/test</code>. I have my router setup for port 80 so it doesn't need a hole punch. My code got a connection. Now I try on other ports and I can't exactly figure out how to punch the hole.</p>
  
  <p>What I have done is (C# code)</p>
  
  <pre><code>var l = new TcpListener(8090);
  l.Start();
  try { var o = new TcpClient(); o.Connect("myserverip", 123); }
  catch(Exception ex) {}
  var e = l.AcceptSocket();
  Console.WriteLine(e.RemoteEndPoint.AddressFamily);
  </code></pre>
  
  <p>I thought maybe I need to setup the local endpoint on the out tcp connection.</p>
  
  <pre><code>TcpClient(new System.Net.IPEndPoint(new System.Net.IPAddress(bytearray), port));
  </code></pre>
  
  <p>I made a mistake and got this exception</p>
  
  <pre><code>The requested address is not valid in its context
  </code></pre>
  
  <p>Fixing up the byte array to <code>192,168,1,5</code> it appears to make outgoing connects correctly. Now that I have a out connection to the remote IP using my listening port I thought wget would be able to connect to me. It wasn't the case</p>
  
  <p>How do I do TCP hole punching?</p>