Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

port

udpclient

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?

like image 616
Syaiful Nizam Yahya Avatar asked Nov 06 '10 02:11

Syaiful Nizam Yahya


People also ask

How do I know what port I am using?

How to find your port number on Windows. Type “Cmd” in the search box. Open “Command Prompt”. Enter the netstat -a command to see your port numbers.

Is port 80 and 8080 the same?

No Port 80 and Port 8080 are not the same. Ports are used to make connections unique and range from 0 to 65535 out of which upto 1024 are called well known ports which are reserved by convention to identify specific service types on a host. 80 is reserved for HTTP.


2 Answers

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.

like image 112
Syaiful Nizam Yahya Avatar answered Sep 30 '22 22:09

Syaiful Nizam Yahya


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.

like image 22
mike Avatar answered Sep 30 '22 22:09

mike