Seems like that case makes doing that a bad idea
Not so, see below.
Is there a way to say "find and use any open port"?
Sure, you could just not bind
or pass NULL
as port
. But then, how would the clients know where to connect to ? You would have to publish this information somewhere.
Back to bind(2)
. If you specify a port of 0
the kernel chooses an ephemeral port when bind is called.
Here's a quote from TLPI:
There are other possibilities than binding a server’s socket to a
well-known address. For example, for an Internet domain socket, the
server could omit the call to bind() and simply call listen(), which
causes the kernel to choose an ephem- eral port for that socket.
Afterward, the server can use getsockname()
to retrieve the address
of its socket. In this scenario, the server must then publish that
address so that clients know how to locate the server’s socket. Such
publication could be done by registering the server’s address with a
centralized directory service application that clients then contact in
order to obtain the address.
Back to your questions:
Also quick question - if I am using both tcp and udp connections in an
application, should they use different ports
Not necessarily. They don't "get mixed up".