5

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

Now in this case If I have to check whether a particular port is in use, how do I do that?

My intention is a port should be used by only one application even though there are multiple interfaces. Is it Ok if I list all the interfaces and bind with the port number with all those interfaces in a loop, or is there any better way to do this checking.

user207421
  • 305,947
  • 44
  • 307
  • 483
Vijay
  • 65,327
  • 90
  • 227
  • 319

1 Answers1

5

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

Except as below.

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

Correct.

Now in this case If I have to check whether a particular port is in use, how do I do that?

See below.

My intention is a port should be used my only one application even though there are multiple interfaces. Is it Ok if I list all the interfaces and bind with the port number with all those interfaces in a loop, or is there any better way to do this checking.

Just bind it to 0.0.0.0:port. In Java that means a null InetAddress and a non-zero port number. If there are any applications listening at specific interfaces and the same port number, you will get a BindException. Conversely, if you are first, it will preclude any other applications from binding to that port in any way at all.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I guess this relates to only IPv4 address... what if there are IPv6 address? can I see any example as well – Vijay Dec 15 '14 at 09:40
  • A null `InetAddress` works for IPv6 as well as IPv4 in Java. I don't know what makes you guess otherwise. – user207421 Dec 15 '14 at 10:22
  • I just read here http://stackoverflow.com/a/11110685/134713 and am getting some doubts about ipv6 – Vijay Dec 15 '14 at 12:51
  • Have you actually *tried* a null `InetAddress`? Or are you just going to keep reading and accumulating 'doubts' forever? – user207421 Dec 15 '14 at 22:52
  • NB there is nothing in your link about using a null `InetAddress` *at all,* let alone anything that says it won't work in IPv6. – user207421 May 11 '17 at 00:07