Yes but how do I tell whether a port is all ready binded?
There are two ways:
- the bind() function returns an error
- you store the list of the ports that you already use (this will however not tell you which ports are used by other applications)
Now I read the documentation and it says I can use: "Socket::AnyPort".
However I want to know if this is safe?
This is the only safe method to get a free port, because the OS chooses it for you. However, since the port is not known in advance, you'll need to transmit it to applications that want to send something to your socket.
Usually, clients don't need to use a known port, only the server needs to. So using Socket::AnyPort is the typical solution to your problem.