10

In Java you can give the number zero as a single parameter for the Socket or DatagramSocket constructor. Java binds that Socket to a free port then. Is it possible to limit the port lookup to a specific range?

2
  • Well, for non-privileged users it is already limited to >1024 on *nix :P Commented Sep 22, 2008 at 15:39
  • Unfortunately we are running on windows ;) Commented Sep 22, 2008 at 15:57

4 Answers 4

7

Hrm, after reading the docs, I don't think you can. You can either bind to any port, then rebind if it is not acceptable, or repeatedly bind to a port in your range until you succeed. The second method is going to be most "efficient".

I am uneasy about this answer, because it is... inelegant, yet I really can't find anything else either :/

Sign up to request clarification or add additional context in comments.

1 Comment

You should also note that there are sometimes security implications in doing a linear search for a free port. If you use port A for client 1, and port A+1 for the next client then client 1 can guess the port your are going to use for some other client.
2

Binding the socket to any free port is (usually) a feature of the operating system's socket support; it's not specific to java. Solaris, for example, supports adjusting the ephemeral port range through the ndd command. But only root can adjust the range, and it affects the entire system, not just your program.

If the regular ephemeral binding behavior doesn't suit your needs, you'll probably have to write your own using Socket.bind().

Comments

2

Here's the code you need:

public static Socket getListeningSocket() {
    for ( int port = MIN_PORT ; port <= MAX_PORT ; port++ )
    {
        try {
            ServerSocket s = new ServerSocket( port );
            return s;      // no exception means port was available
        } catch (IOException e) {
            // try the next port
        }
    }
    return null;   // port not found, perhaps throw exception?
}

1 Comment

You should rather catch <code>BindException</code>, which is the one launched when the port is already in use.
0

You might glance at the java code that implements the function you are using. Most of the java libraries are written in Java, so you might just see what you need in there.

Assuming @Kenster was right and it's a system operation, you may have to simply iterate over ports trying to bind to each one or test it. Although it's a little painful, it shouldn't be more than a few lines of code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.