tags:

views:

4282

answers:

6

How to programmatically find availability of a port in a given machine using java?i.e given a port number whther it is already being used .

A: 

Here is your answer.

Update: Obviously the answer is to pay attention to Exceptions.

try {
    serverSocket = new ServerSocket(4444);
} catch (IOException e) {
    // The port is not available.
    System.out.println("Could not listen on port: 4444");
    System.exit(-1);
}
Fernando Miguélez
Where exactly on this page is the answer to the question? I can't find it. The only relevant part I found is "When writing a server, choose a port that is not already dedicated to some other service," and it does't answer the question.
Hosam Aly
@Hosam: Thats the answer, precisely. Spoon feeding is not at all necessary. +1
Adeel Ansari
What would be the best way to restrict the user to using available ports only in Java ? restarting the application and retrying doesn't look like a solution
George Profenza
A: 

ServerSocket can do that.

Bombe
How exactly can it do it?
Hosam Aly
Spencer has shown a fine example of it. Doesn't qualify for a negative, IMO.
Adeel Ansari
When somebody talks about finding out if a port is already used I assume he has at least basic knowledge about sockets. The ServerSocket documentation then contains all you need to know.
Bombe
Most useless answer ever!
PintSizedCat
+7  A: 

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.

bool portTaken = false;
ServerSocket socket = null;
try {
    serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
    portTaken = true;
} finally { 
    // Clean up
    if (socket != null) socket.close(); 
}
Spencer Ruport
Use finally for cleanup (try { ... } catch { ... } finally { if (socket != null) socket.close(); }
Hosam Aly
You can also set "portTaken = (socket == null);" at the end instead of doing it in the catch.
Hosam Aly
Thanks for the recommendation.
Spencer Ruport
This attempts to bind to the socket on all (0.0.0.0) interfaces. You can use explicit addresses to check specific ports on specific addresses. see http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#ServerSocket(int,%20int,%20java.net.InetAddress)
cletus
I didn't feel that fell within the intended scope of the author's question.
Spencer Ruport
A minor mistake that an initialization should be:ServerSocket serverSocket = null;
royalGhost
Is there a way to do it without try/catch? I wouldn't mind using *any* available port for my purposes, but iterating over port numbers and try/catch-ing over each one until I find a free one is a little wasteful. Isn't there a 'native boolean available(int)' method somewhere, which just checks?
Oz
new SeverSocket(0) will automatically select a free port .
Spencer Ruport
+9  A: 

This is the implementation coming from the apache mina proyect:

/**
 * 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;
}

Those guys are checking The DatagramSocket as well to check if the port is avaliable in UDP and TCP.

Hope this help.

David Santamaria
A: 

any predefined method to check if the port is available or not ?????

A: 

Don't forget to call setReuseAddress(true); (as per the Apache Mina example), or you'll find that the port isn't free when you come to use it!

Neil