Java 如何找到可用的端口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2675362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:41:46  来源:igfitidea点击:

How to find an available port?

javanetworkingsocketsport

提问by Roman

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.

我想启动一个监听端口的服务器。我可以明确指定端口并且它可以工作。但我想以自动方式找到一个端口。在这方面,我有两个问题。

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

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

  1. 我应该在哪个端口号范围内搜索?(我使用了端口 12345、12346 和 12347,它很好)。

  2. 如何确定给定端口是否未被其他软件占用?

采纳答案by Graham Edgecombe

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

如果您不介意使用的端口,请为ServerSocket 构造函数指定端口 0,它将侦听任何空闲端口。

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");
}

回答by OscarRyz

If your server starts up, then that socket was not used.

如果您的服务器启动,则未使用该套接字。

EDIT

编辑

Something like:

就像是:

ServerSocket s = null ;

try { 
    s = new ServerSocket( 0 ); 
} catch( IOException ioe ){
   for( int i = START; i < END ; i++ ) try {
        s = new ServerSocket( i );
    } catch( IOException ioe ){}
}
// At this point if s is null we are helpless
if( s == null ) {
    throw new IOException(
       Strings.format("Unable to open server in port range(%d-%d)",START,END));
}

回答by Andy Johnson

According to Wikipedia, you should use ports 49152to 65535if you don't need a 'well known' port.

根据Wikipedia,如果您不需要“众所周知”的端口4915265535则应该使用端口。

AFAIK the only way to determine wheter a port is in use is to try to open it.

AFAIK 确定端口是否正在使用的唯一方法是尝试打开它。

回答by Maurice Perry

If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.

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

回答by f1sh

See http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#ServerSocket%28int%29

http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#ServerSocket%28int%29

Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.

创建一个绑定到指定端口的服务器套接字。端口 0 在任何空闲端口上创建套接字。

回答by jopa

The Eclipse SDK contains a class SocketUtil, that does what you want. You may have a look into the git source code.

Eclipse SDK 包含一个类SocketUtil,它可以满足您的需求。您可以查看 git源代码

回答by extraneon

It may not help you much, but on my (Ubuntu) machine I have a file /etc/services in which at least the ports used/reserved by some of the apps are given. These are the standard ports for those apps.

它可能对您没有多大帮助,但在我的(Ubuntu)机器上,我有一个文件 /etc/services,其中至少提供了一些应用程序使用/保留的端口。这些是这些应用程序的标准端口。

No guarantees that these are running, just the default ports these apps use (so you should not use them if possible).

不能保证这些正在运行,只是这些应用程序使用的默认端口(因此如果可能,您不应该使用它们)。

There are slightly more than 500 ports defined, about half UDP and half TCP.

定义的端口略多于 500 个,大约一半是 UDP,一半是 TCP。

The files are made using information by IANA, see IANA Assigned port numbers.

这些文件是使用 IANA 提供的信息制作的,请参阅IANA 分配的端口号

回答by Peter Lawrey

This works for me on Java 6

这在 Java 6 上对我有用

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

回答by oberlies

If you want to create your own server using a ServerSocket, you can just have it pick a free port for you:

如果你想使用 a 创建你自己的服务器ServerSocket,你可以让它为你选择一个免费端口:

  ServerSocket serverSocket = new ServerSocket(0);
  int port = serverSocket.getLocalPort();

Other server implementations typically have similar support. Jettyfor example picks a free port unless you explicitly set it:

其他服务器实现通常有类似的支持。例如,除非您明确设置,否则Jetty 会选择一个空闲端口:

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  // don't call: connector.setPort(port);
  server.addConnector(connector);
  server.start();
  int port = connector.getLocalPort();