Question

This is the first time I'm working with IPEndPoint, so pardon my lack of experience.

If I create an IPEndPoint like this:

IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.25"), 0);

Is it possible that port 0 will already be in-use such that this will produce an exception? Is there any type of convention here for which local port number to use? Should I just use a randomly generated number that's less than 65,536? Is there a best or safest approach to choosing a port and does it even matter?

The use case in this particular instance is just for me to learn more. I'm fiddling with sending UDP broadcast WOL packets at the moment, but later I expect to get into a bit more complicated code. I just want to make sure I understand best practice.

Was it helpful?

Solution

According to IANA

Port numbers are assigned in various ways, based on three ranges: System Ports (0-1023), User Ports (1024-49151), and the Dynamic and/or Private Ports (49152-65535); the difference uses of these ranges is described in [RFC6335]. System Ports are assigned by IETF process for standards-track protocols, as per [RFC6335]. User Ports are assigned by IANA using the "IETF Review" process, the "IESG Approval" process, or the "Expert Review" process, as per [RFC6335]. Dynamic Ports are not assigned.

Also from the UdpClient(port) ctor MSDN documentation:

If you pass 0 to the constructor, the underlying service provider will assign a port number.

OTHER TIPS

First, you would want to check to see if you are interfering with any standard windows service ports

Random in that case would be a very bad way to go, the port may be in use by some other app.

But you can always go here and choose something that is unassigned.

There, the IANA says

The Dynamic and/or Private Ports are those from 49152 through 65535

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top