How to know the port number used by c# UdpClient?

Here are the answer to my questions.

UdpClient udpClient = new UdpClient(0));
Console.WriteLine("UDP port : " + ((IPEndPoint)udpClient.Client.LocalEndPoint).Port.ToString());

0 as the constructor parameter set the app to automatically find free udp port. ((IPEndPoint)udpClient.Client.LocalEndPoint)).Port.ToString() is used to find the port number.


I believe you can use the Socket.RemoteEndPoint property to know what the IP/Port of the client connected to the server is (you know your local IP/port because you started the socket on that port, but it is also available through the LocalEndPoint property.

Also see the MSDN UdpClient for a simple example on how to use the UdpClient properly.

Tags:

C#

Port

Udpclient