Jul 07

Recently the need has risen to find out a free port on a local network interface, so that an application can bind to it. At first thought, there is no real need to have an API which reveals a free port on the system: If the developer wishes to bind to an unspecified port, ServerSocket with ’0′ as the port number would bind to a free port on the network interface. However, by using that constructor, the class automatically binds to that port. So, in order to find a free port:


public static int findFreePort()
             throws IOException {
  ServerSocket server =
    new ServerSocket(0);
  int port = server.getLocalPort();
  server.close();
  return port;
}

The action is expensive, but not as some of the implementation I’ve seen which tries random port numbers and loop as long as an exception is raised.

But why find a free port anyway? Well, I’ve encountered two cases where I require such knowledge, but I’m sure others exist.

The first is when remote debugging is to be enabled, using Java Platform Debugger Architecture (JPDA). The current way to enable remote debugging is via the -Xrunjdwp:transport=dt_socket,server=y,address=port flag to the VM. The problem: Choosing a port for an application is tedious, especially when deployment requires to raise many different applications, all needing remote debugging at some point. The solution is not to specify the port; then, a free port is used and printed out to standard output – Which is no help at all, really.

The second is when remote management is needed, using Java Management Extensions (JMX). Again, the way to allow remote management is through a flag, such as -java.management.remote.port=port. We encounter the same problem as before: When having to launch a lot of different applications, managing which application gets which port is tedious and redundant.

For these two cases, automatic port retrieval in a way which can be later reported to a management application is essential. The way I presented before should work, as long as there is one single management application choosing these ports for the loaded application which needs to be remotely managed or debugged (or whatever you need them to be), so there isn’t a chance for port collisions.

  • Share/Bookmark

Leave a Reply

Chaotic Java is Digg proof thanks to caching by WP Super Cache