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).
我应该在哪个端口号范围内搜索?(我使用了端口12345、12346和12347,很好)。
-
How can I find out if a given port is not occupied by another software?
如何查明给定的端口是否被其他软件占用?
13 个解决方案
#1
228
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构造函数指定一个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");
}
#2
48
If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.
如果您将0作为端口号传递给ServerSocket的构造函数,它将为您分配一个端口。
#3
26
Starting from Java 1.7 you can use try-with-resources like this:
从Java 1.7开始,您可以使用这样的试用资源:
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.
如果您需要在特定的接口上找到一个打开的端口,请检查ServerSocket文档以获取其他构造函数。
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.
警告:使用此方法返回的端口号的任何代码都受到竞争条件的限制——在我们关闭ServerSocket实例之后,另一个进程/线程可能会立即绑定到相同的端口。
#4
21
According to Wikipedia, you should use ports 49152
to 65535
if you don't need a 'well known' port.
根据*,如果你不需要一个“众所周知”的端口,你应该使用端口49152到65535。
AFAIK the only way to determine wheter a port is in use is to try to open it.
确定端口是否被使用的唯一方法是尝试打开它。
#5
16
If you need in range use:
如果您需要在范围内使用:
public int nextFreePort(int from, int to) {
int port = randPort(from, to);
while (true) {
if (isLocalPortFree(port)) {
return port;
} else {
port = ThreadLocalRandom.current().nextInt(from, to);
}
}
}
private boolean isLocalPortFree(int port) {
try {
new ServerSocket(port).close();
return true;
} catch (IOException e) {
return false;
}
}
#6
12
If you use Spring you may try http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/util/SocketUtils.html#findAvailableTcpPort--
如果您使用Spring,可以尝试http://docs.spring.io/docs/4.0.5.release/javadoc - api/org/springframework/util/socketutils.html # findabletcpport—
#7
10
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源代码。
#8
6
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 % 28 int % 29
Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.
创建一个绑定到指定端口的服务器套接字。端口0在任意空闲端口上创建套接字。
#9
5
This works for me on Java 6
这在Java 6上对我很有用。
ServerSocket serverSocket = new ServerSocket(0);
System.out.println("listening on port " + serverSocket.getLocalPort());
#10
4
If you want to create your own server using a ServerSocket
, you can just have it pick a free port for you:
如果您想使用ServerSocket创建您自己的服务器,您可以让它为您选择一个空闲端口:
ServerSocket serverSocket = new ServerSocket(0);
int port = serverSocket.getLocalPort();
Other server implementations typically have similar support. Jetty for 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();
#11
4
I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:
我最近发布了一个小的库,用于在进行测试时实现这一点。Maven的依赖是:
<dependency>
<groupId>me.alexpanov</groupId>
<artifactId>free-port-finder</artifactId>
<version>1.0</version>
</dependency>
Once installed, free port numbers can be obtained via:
一旦安装,免费端口号可通过:
int port = FreePortFinder.findFreeLocalPort();
#12
3
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));
}
#13
2
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分配的端口号。
#1
228
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构造函数指定一个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");
}
#2
48
If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.
如果您将0作为端口号传递给ServerSocket的构造函数,它将为您分配一个端口。
#3
26
Starting from Java 1.7 you can use try-with-resources like this:
从Java 1.7开始,您可以使用这样的试用资源:
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.
如果您需要在特定的接口上找到一个打开的端口,请检查ServerSocket文档以获取其他构造函数。
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.
警告:使用此方法返回的端口号的任何代码都受到竞争条件的限制——在我们关闭ServerSocket实例之后,另一个进程/线程可能会立即绑定到相同的端口。
#4
21
According to Wikipedia, you should use ports 49152
to 65535
if you don't need a 'well known' port.
根据*,如果你不需要一个“众所周知”的端口,你应该使用端口49152到65535。
AFAIK the only way to determine wheter a port is in use is to try to open it.
确定端口是否被使用的唯一方法是尝试打开它。
#5
16
If you need in range use:
如果您需要在范围内使用:
public int nextFreePort(int from, int to) {
int port = randPort(from, to);
while (true) {
if (isLocalPortFree(port)) {
return port;
} else {
port = ThreadLocalRandom.current().nextInt(from, to);
}
}
}
private boolean isLocalPortFree(int port) {
try {
new ServerSocket(port).close();
return true;
} catch (IOException e) {
return false;
}
}
#6
12
If you use Spring you may try http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/util/SocketUtils.html#findAvailableTcpPort--
如果您使用Spring,可以尝试http://docs.spring.io/docs/4.0.5.release/javadoc - api/org/springframework/util/socketutils.html # findabletcpport—
#7
10
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源代码。
#8
6
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 % 28 int % 29
Creates a server socket, bound to the specified port. A port of 0 creates a socket on any free port.
创建一个绑定到指定端口的服务器套接字。端口0在任意空闲端口上创建套接字。
#9
5
This works for me on Java 6
这在Java 6上对我很有用。
ServerSocket serverSocket = new ServerSocket(0);
System.out.println("listening on port " + serverSocket.getLocalPort());
#10
4
If you want to create your own server using a ServerSocket
, you can just have it pick a free port for you:
如果您想使用ServerSocket创建您自己的服务器,您可以让它为您选择一个空闲端口:
ServerSocket serverSocket = new ServerSocket(0);
int port = serverSocket.getLocalPort();
Other server implementations typically have similar support. Jetty for 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();
#11
4
I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:
我最近发布了一个小的库,用于在进行测试时实现这一点。Maven的依赖是:
<dependency>
<groupId>me.alexpanov</groupId>
<artifactId>free-port-finder</artifactId>
<version>1.0</version>
</dependency>
Once installed, free port numbers can be obtained via:
一旦安装,免费端口号可通过:
int port = FreePortFinder.findFreeLocalPort();
#12
3
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));
}
#13
2
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分配的端口号。