How to find an available port?

I want to start a server which listen to a port. I can specify port explicitly and it works. But I would like to find a port in an automatic way. In this respect I have two questions.

  • In which range of port numbers should I search for? (I used ports 12345, 12346, and 12347 and it was fine).

  • How can I find out if a given port is not occupied by another software?


  • If you don't mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.

    ServerSocket s = new ServerSocket(0);
    System.out.println("listening on port: " + s.getLocalPort());
    

    If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:

    public ServerSocket create(int[] ports) throws IOException {
        for (int port : ports) {
            try {
                return new ServerSocket(port);
            } catch (IOException ex) {
                continue; // try next port
            }
        }
    
        // if the program gets here, no port in the range was found
        throw new IOException("no free port found");
    }
    

    Could be used like so:

    try {
        ServerSocket s = create(new int[] { 3843, 4584, 4843 });
        System.out.println("listening on port: " + s.getLocalPort());
    } catch (IOException ex) {
        System.err.println("no available ports");
    }
    

    如果您将0作为端口号传递给ServerSocket的构造函数,它将为您分配一个端口。


    Starting from Java 1.7 you can use try-with-resources like this:

      private Integer findRandomOpenPortOnAllLocalInterfaces() throws IOException {
        try (
            ServerSocket socket = new ServerSocket(0);
        ) {
          return socket.getLocalPort();
    
        }
      }
    

    If you need to find an open port on a specific interface check ServerSocket documentation for alternative constructors.

    Warning: Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance.

    链接地址: http://www.djcxy.com/p/30292.html

    上一篇: 如何杀死在Linux的特定端口上运行的进程?

    下一篇: 如何找到一个可用的端口?