如何找到可用的端口? [英] 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.
-
我应该在哪个端口号范围内搜索? (我使用了端口12345,12346和12347,它很好)。
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?
推荐答案
如果您不介意使用的端口,请指定端口0到 ServerSocket构造函数它会监听任何空闲端口。
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");
}
可以像这样使用:
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");
}
这篇关于如何找到可用的端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!