问题描述
在OS X上,当在特定端口上为所有接口创建服务器套接字时,新的服务器套接字可以使用相同的端口绑定到localhost
并接受连接。
我希望与localhost
的绑定会失败,就像在Linux中尝试绑定一样(我在Ubuntu上专门尝试过)。
OS X上的行为对我来说很奇怪,因为在所有接口上侦听时,与localhost
的客户端连接都起作用,但是新服务器可以在同一端口上绑定localhost
并接受新连接第一听众的。
套接字如何在所有接口上侦听,并如何防止其他套接字使用OS X上的相同端口绑定到localhost
?
以下测试在Mac上通过了,在Ubuntu上失败了,但是在两者上都应该失败。
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
public class MinimalTest {
@Test
public void listenOnAllInterfacesAndLocalhost() throws IOException {
final int port = 12340;
try (ServerSocket allInterfaces = new ServerSocket(port);
ServerSocket onlyLocalhost = new ServerSocket(port,100,Inet4Address.getByName("localhost"));) {
Assert.assertEquals(allInterfaces.getLocalPort(),port);
Assert.assertEquals(onlyLocalhost.getLocalPort(),port);
Assert.assertTrue(allInterfaces.isBound());
Assert.assertTrue(onlyLocalhost.isBound());
}
}
}
我尝试过的事情:
- 使用
Inet4Address.getByName("0.0.0.0")
或Inet6Address.getByName("::")
显式监听所有接口,但无论是否具有此规范,lsof
均显示在所有接口上的监听:*:12340
- 我切换了绑定的顺序(首先是
localhost
,然后是所有接口),并且切换了来自不同进程的绑定,但是OS X仍然允许绑定。 - 我搜索了类似的问题,但没有发现此问题... Binding to all interfaces of a single network interface multiple interface bind on same port Can I bind multiple servers to the same TCP port? Can socket client and server on the same computer bind to same port?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)