From a posting at the DIA newsgroup:

The sun java page says passing zero to Server Socket gets the next available
port and getLocalPort() tells us what it is. The simple code at the bottom
seems to work.  No promises, but it is a start. 
sun sockets page
 
// Elliott. Code to get another available port
// uses passing 0, and then a query to see what you got.

import java.io.*;
import java.net.*;

public class GetAPort {
 public static void main(String[] a) {
   try {
     // pass zero and get something that is free:
     ServerSocket s = new ServerSocket(0);
     System.out.println("Just got a random port at: "  + s.getLocalPort());
   }
   catch (IOException ioe) {System.err.println(ioe);
   }
   // no cleanup in example, so leaves open connections.
 }
}

java GetAPort
Just got a random port at: 2411

c:\dp\420\java\dia>java GetAPort
java GetAPort
Just got a random port at: 2412

c:\dp\420\java\dia>java GetAPort
java GetAPort
Just got a random port at: 2413