How to know the port number used by c# UdpClient? [duplicate]
Asked Answered
P

3

8

I am creating a client server application using c sharp. The server is using tcplistener with fixed port number. the client connect to the server using tcpclient. Once connected, both client and server communicate using this connection. The application then create new udp connection to send and receive message. Since the server suppose to accept multiple connection from single client, i have to differentiate each connection with different port. In order to do this, i have to first 1. at server, create a udpclient (automatically use unused udp port at the server). 2. sends the port number used by the server udpclient to the client. 3. the client sends data to the server using specified port number.

The problem is, how to create a udpclient where you can know the port number used?

Prenotion answered 6/11, 2010 at 2:36 Comment(0)
P
18

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.

Prenotion answered 6/11, 2010 at 20:11 Comment(2)
Sadly, at least in .NET 4.0, the system never sets the Port field of a UDP socket. And since it is a get-only property, you can't manually set it either.Mauney
OOPS. I should have said: The system does not set the Port on RAW UDP Sockets when you bind. it does on DGRAM Sockets.Mauney
I
2

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.

Inerney answered 6/11, 2010 at 7:50 Comment(0)
S
0

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

You should use a Socket object to do that, which allows you to monitor a port for incoming UDP messages. Then no doubt you can tell the client which port the server is monitoring.

Sericin answered 6/11, 2010 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.