How to know what port to have a program listen on

Caders117 :

I'm writing a chat program using sockets and Java and I have to specify a port that the servers listen on.

Here is the the questions I have:

  1. How can I be sure that that port is always free?

  2. Does it matter if another program is also listening on that port?

  3. If the port has to be free and the default port is occupied, how would I notify the clients of a change in port number?

  4. Should I just make it so the server keeps trying to bind to a new port, incrementing the port number until it finds a free port?

imricardoramos :

How can I be sure that that port is always free?

You can use "netstat" to check whether a port is available or not. You can list all the ports being used by a service via:

netstat -anp

If you want to search for a specific port you can use:

netstat -anp | find "port number", eg netstat -anp | find ":8080".

Does it matter if another program is also listening on that port?

From a traditional look, Yes, for TCP you can only have one application listening on the same port and same local ip address at one time. You may be able to use the same port by having multiple local IP adresses either by using multiple network cards or virtual network interfaces.

However, it seems that using the SO_REUSEPORT socket option you may be able to reuse it, check this for more information.

If the port has to be free and the default port is occupied, how would I notify the clients of a change in port number? Should I just make it so the server keeps trying to bind to a new port, incrementing the port number until it finds a free port?

Personally I would either choose a port that is always free or a small list of ports I knew would be usually free and try one by one.

The general rules of thumb for choosing a port include choosing at least a 4 digit number and avoid anything below 1024. Also, even if the port was already in use by another service, you could re-assign it to listen to another port, its your network after all.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85091&siteId=1