I am trying to generate a random port number for a TCP connection. From : http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers I know that the range of ports is from 1024 to 49151 are not reserved, but some of them are UDP only, how can I generate only valid TCP port numbers?
If you bind to port 0, the OS will select a valid, not-in-use port.
If you need random as opposed to arbitrary, anything from 49152–65535 should be safe for automatic use like this, so just select a random number within that range. (you may have to retry if that port turns out to be in use, however.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With