HOW WOULD I CHOOSE IN JAVA THAT WHICH PORT IS FREE TO USE FOR SERVERSOCKET OR SOCKET?

Linda Perla

Total Post:13

Points:93
Posted by  Linda Perla
Java 
 439  View(s)
Ratings:
Rate this:
I'm working on java. How would I check that a port is free to use for a ServerSocket? Moreover when a Socket is returned by the accept() function is it given a port and IP address by default or I would have to specify that too?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How would I choose in java that which port is free to use for ServerSocket or Socket?

    You wouldn't need to check. You would specify port 0, which causes the system to give you a free port.
    Yes , It is given the IP address that the peer connected to, and the same port as the listening socket.
    No we won't need to specify the port and IP address.

    You can use the java.net.ServerSocket constructor with port 0 which tells ServerSocket to find a free port.
    Example :
    int port = -1;
    try {
        ServerSocket socket = new ServerSocket(0);
        // here's your free port
        port = socket.getLocalPort();
        socket.close();

    catch (IOException ioe) {}


    Also, we can use Use Try catch to find a free port:
    private static int port=9000;
    public static int detectPort(int prt)
    {
    try{
    //connect to port
    }
    catch(Exception e)
    {
    return detectPort(prt+1);
    }
    return prt;
    }
    // Write detectPort(port); inside main

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!