title: C# UDP cannot listen on a port that has already been used to send data?
body: <p>I am new to UDP/networking programming, and I am trying to create a chat board via UDP.</p>
  
  <p>My ultimate aim is to do UDP hole-punching (something of a similar concept to Skype), so I need to listen on the same port as the port used to send data, otherwise the NAT will drop the incoming packet.</p>
  
  <p>I have tried doing</p>
  
  <pre><code>server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  </code></pre>
  
  <p>but I am unable to receive data from a port that has been used to send data.</p>
  
  <p>This is what my code for the listener looks like (it is on a separate thread) (it is adapted from another tutorial on the web):</p>
  
  <pre><code>        byte[] data = new byte[1024];
          IPEndPoint ipep = new IPEndPoint(IPAddress.Any, (int)e.Argument);
          UdpClient newsock = new UdpClient();
          newsock.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
          newsock.Client.Bind(ipep);
          IPEndPoint from_ip = new IPEndPoint(IPAddress.Any, 0);
          Invoke(new Action(() =&gt; { WriteOnScreen("Done!"); }));
          while (true)
          {
              data = newsock.Receive(ref from_ip);
              string s = Encoding.ASCII.GetString(data, 0, data.Length);
              //more stuff to deal with s
          }
  </code></pre>
  
  <p>This is my sender:</p>
  
  <pre><code>        UdpClient server = new UdpClient();
          server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
          server.Connect(CurrIP, CurrPort);
  </code></pre>
  
  <p>The method server.Close() will be only called when the application is terminated by the user.</p>
  
  <p>When I checked the local port of the sender, I realised that the listener fails to listen only when the local port of the receiver "(int)e.Argument" is equal to the local port of the sender.  When I set the receiving port to a different port, I am able to receive packets.</p>
  
  <p>Also, I can't create more instances of UdpClient as my local port for each UdpClient will be different, and so I would be unable to do hole-punching.</p>
  
  <p>I searched many places already, and no one seems to have this problem...</p>
  
  <p>I believe that there is an easier way...</p>