How do you decide what port to use?
Solution 1:
I think you've pretty much answered your question as much as is possible; there isn't really a strict rule you can follow here beyond what you've said. But generally:
- Look at the IANA list and pick a port that's not in use.
- Pick a port number that is easy to remember.
- Don't fix the port number in your code. Some other product may have picked the same port as you and you never know when you'll have to co-exist on a server, so put the port number in a configuration file somewhere so it can be changed without a recompile if necessary. The ability to change port number can also be helpful for getting through firewalls without having to get them reconfigured. (You can always default to your chosen value if the configuration file doesn't exist.)
- There is an argument that you don't want to pick something too high as you may conflict with the range used for ephemeral ports. It's not that likely that you'll get hit by this, but it's a hard problem to debug when it happens.
(And if you want a tip for picking memorable port numbers, I once worked with someone who remembered port numbers based around the telephone extensions of his co-workers.)
Solution 2:
Some easy to remember and appropriately nerdy unassigned (per IANA) ports:
27182 (e)
31415 (pi)
60221 (avagadro's)
Solution 3:
During testing... always port #666 ;)
Solution 4:
How about:
defaultPort = (new Random()).Next(48620, 49150);