1

This question is almost similar to this previous question Sockets: Discover port availability using Java. But somehow its not working properly when I check the derby listening port.

public static boolean isPortavailable(int 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(ss != null){
        try{
            ss.close();
            ds.close();
        }
        catch(IOException e){
            /* should not be thrown */
        }
        }
    }
    return false;
}

Here is my main method

public static void main(String[] args){
    System.out.println("Derby:"+isPortAvailable(1527));
    System.out.println("Jetty:"+isPortAvailable(7080));
    System.out.println("Tomcat:"+isPortAvailable(8084));
}

I started services with the port for derby 1527, jetty 7080 and tomcat 8084. when I run this main method it gives the following result

Derby:true
Jetty:false
Tomcat:false

I am unable to find why Its giving wrong answer for derby, can anyone help. Thanks

Community
  • 1
  • 1
vels4j
  • 11,208
  • 5
  • 38
  • 63
  • Calling setReuseAddress() after you've already bound the socket to a port accomplishes precisely nothing, and calling it at all in a program of this nature is completely pointless. – user207421 Oct 26 '12 at 20:21
  • @EJP : that code was from apache project http://svn.apache.org/viewvc/camel/trunk/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java?view=markup#l130 I don't have much idea. – vels4j Oct 27 '12 at 04:16
  • Check this [answer](http://stackoverflow.com/a/13826145/2546579) for this [question](http://stackoverflow.com/q/434718/2546579) by – hannunehg Oct 26 '15 at 08:02

0 Answers0