Check your port if there are multiple interfaces.

I know that for TCP we can only have one application listening on one port at a time. Now, if you had 2 network cards, you could listen to one application on the first IP address, and the second on the second IP address, using the same port number.

Now in this case, if I need to check if a specific port is being used, how to do it?

My intention is a port that should be used by only one application, although there are several interfaces. Well, if I have listed all the interfaces and contact the port number with all these interfaces in a loop, or there is a better way to do this check.

+5
source share
1 answer

I know that for TCP we can only have one application listening on one port at a time.

Except below.

Now, if you had 2 network cards, one application can listen on the first IP address and the second on the second IP address using the same port number.

Right.

Now in this case, if I need to check if a specific port is being used, how to do it?

See below.

My intention is a port that should be used only by my only application, although there are several interfaces. Well, if I have listed all the interfaces and contact the port number with all these interfaces in a loop, or there is a better way to do this check.

Just bind it to 0.0.0.0:port . In Java, this means InetAddress zero and a non-zero port number. If there are applications listening on certain interfaces and the same port number, you will get a BindException . Conversely, if you are the first, this will not allow any other applications to bind to this port at all.

+5
source

Source: https://habr.com/ru/post/1209058/


All Articles