First of all,
htons
won't give you any information on unused port. It does something completely different:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms738557%28v=vs.85%29.aspx[
^],
http://linux.die.net/man/3/htons[
^].
To get this port number, you need to interrogate a set of ports to find out which port is busy. I don't want to discuss this now, because you did not even tag your platform in your question. But first, you need to determine what set of ports you can use in principle. You should not use well-known, reserved and registered ports. There is only one authority to regulate this — IANA, so you always need to consult this page:
http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml[
^]. In the application like yours you always need to select a port from Dynamic and/or Private Ports (49152-65535).
But how do you want to inform the client side part of application about a port number to use? Think about it. To read this information you need to connect a server computer, to connect it, you need to know what port to use, well,
you understand…. So, anyway, eventually you will need to use some fixed port anyway. You can even have a special service working on fixed port to answer clients what port to use, but why? You might want to use some
well-know port number, but what well-known application is designed to serve-up port information? I don't know such application. In principle, it can be, say, FTP or HTTP service which would use on a default port number and give you a file a Web page with port numbers for all your application. But… how many applications do you have? Do you really want to get into this? Maybe well-selected fixed port is still accessible? Just think about it.
—SA