Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the port number assigned to a UDP client (in .net/C#)?

Tags:

c#

udp

udpclient

If I create a socket using

var socket = new UdpClient(0,AddressFamily.InterNetwork);

How do I then find the port of the socket?

I'm probably being daft, but I'm not having luck in MSDN/Google (probably because it is 4:42 on a Friday and the sun is shining).

Background:

What I want to do is find an open port, and then report to another process to forward messages to me on that port. There may be multiple clients, so I don't want to used a fixed port.

Thanks.

like image 660
Charley Rathkopf Avatar asked Aug 21 '09 23:08

Charley Rathkopf


1 Answers

UdpClient is a wrapper around the Socket class which exposes the endpoint it's bound to through the LocalEndPoint property. Since you're using an UDP/IP client it's an IPEndPoint which has the desired Port property:

int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port;
like image 197
dtb Avatar answered Sep 28 '22 02:09

dtb