我想要实现的目标
将服务器绑定(bind)到临时端口以进行单元测试。
我的问题:
使用 1.5.0_22 JDK,我尝试按照 javadoc 使用端口 0 将 InetSocketAddress 绑定(bind)到一个临时端口上,但我无法从地址对象中找到一种方法来知道它绑定(bind)到哪个端口,所以我不能对我的客户进行相应配置:
InetSocketAddress address = new InetSocketAddress(0);
assertThat(address.isUnresolved(), is(false));
assertThat(address.getPort(), is(0));
我可能没有正确理解 javadoc 语句:
A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation.
但是即使在我的服务器监听套接字之后检查端口(我假设绑定(bind)已经发生)也不会返回任何其他内容,但 0(以下使用 http://simpleweb.sourceforge.net/ 库):
Container httpServer = new Container() {
public void handle(Request req, Response resp) {
}
};
SocketConnection connection = new SocketConnection(httpServer);
InetSocketAddress address = new InetSocketAddress(0);
connection.connect(address);
assertThat(address.isUnresolved(), is(false));
assertThat(address.getPort(), is(0));
使用 nmap 我什至没有看到绑定(bind)端口,所以我假设我的理解是不正确的。有帮助吗?
最佳答案
最初包含端口 0 的 InetSocketAddress
不会被 connect()
更新以表示绑定(bind)到的实际端口。调用 connection.getLocalPort()
或 ((InetSocketAddress)connection.getLocalSocketAddress()).getPort()
获取绑定(bind)端口。
关于java - java InetSocketAddress 绑定(bind)到哪个临时端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344357/