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?.
This is the implementation coming from the Apache camel project:
They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.
Hope this helps.
In my case I had to use DatagramSocket class.
Don't forget to import first
I have Tried something Like this and it worked really fine with me
The following solution is inspired by the SocketUtils implementation of Spring-core (Apache license).
Compared to other solutions using
Socket(...)
it is pretty fast (testing 1000 TCP ports in less than a second):For Java 7 you can use try-with-resource for more compact code:
It appears that as of Java 7, David Santamaria's answer doesn't work reliably any more. It looks like you can still reliably use a Socket to test the connection, however.