How do I programmatically determine the availability of a port in a given machine using Java?
i.e given a port number, determine whether it is already being used or not?.
How do I programmatically determine the availability of a port in a given machine using Java?
i.e given a port number, determine whether it is already being used or not?.
The try/catch socket based solutions , might not yield accurate results (the socket address is "localhost" and in some cases the port could be "occupied" not by the loopback interface and at least on Windows I've seen this test fails i.e. the prot falsely declared as available).
There is a cool library named SIGAR , the following code can hook you up :
If you're not too concerned with performance you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.
EDIT: If all you're trying to do is select a free port then
new SocketServer(0)
will find one for you.In my case it helped to try and connect to the port - if service is already present, it would respond.