How to find out the port number used by C # UdpClient?

I am building a client server application using c sharp. The server uses a tcplistener with a fixed port number. the client connects to the server using tcpclient. After connecting, the client and server exchange data using this connection. The application then creates a new udp connection to send and receive the message. Since the server allows multiple connections from one client, I have to distinguish between each connection to a different port. To do this, I must first 1. On the server, create udpclient (automatically use the unused udp port on the server). 2. Sends the port number used by the udpclient server to the client. 3. The client sends data to the server using the specified port number.

The problem is how to create udpclient, where can you find out the port number that is being used?

+5
source share
3 answers

Here is the answer to my questions.

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

0 as a constructor parameter, so that the application automatically finds a free udp port. ((IPEndPoint)udpClient.Client.LocalEndPoint)).Port.ToString()used to find the port number.

+12
source

I suppose you can use the Socket.RemoteEndPoint property to find out that the IP / port of the client is connected to the server (you know your local IP / port because you started the socket on this port, but it is also accessible through the LocalEndPoint property.

. MSDN UdpClient , UdpClient.

+2

I think you cannot use server-side UdpClient to achieve your goal, as it does not have a Bind method to bind to IPEndPoint.

To do this, you must use the Socket object, which allows you to control the port for incoming UDP messages. Then, without a doubt, you can tell the client which port is the server’s monitoring port.

0
source

All Articles