Sockets: Discover port availability using Java
This is the implementation coming from the Apache camel project:
/** * Checks to see if a specific port is available. * * @param port the port to check for availability */public static boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false;}
They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.
Hope this helps.
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.
private static boolean available(int port) { System.out.println("--------------Testing port " + port); Socket s = null; try { s = new Socket("localhost", port); // If the code makes it this far without an exception it means // something is using the port and has responded. System.out.println("--------------Port " + port + " is not available"); return false; } catch (IOException e) { System.out.println("--------------Port " + port + " is available"); return true; } finally { if( s != null){ try { s.close(); } catch (IOException e) { throw new RuntimeException("You should handle this error." , e); } } }}