I am new to UDP/networking programming, and I am trying to create a chat board via UDP.
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.
I have tried doing
server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
but I am unable to receive data from a port that has been used to send data.
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):
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(() => { 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
}
This is my sender:
UdpClient server = new UdpClient();
server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Connect(CurrIP, CurrPort);
The method server.Close() will be only called when the application is terminated by the user.
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.
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.
I searched many places already, and no one seems to have this problem...
I believe that there is an easier way...
You need to use the same UdpClient
for both sending and receiving.