在 OS X 上,当在所有接口的特定端口上创建服务器套接字时,新的服务器套接字可以绑定到localhost相同的端口并接受连接。我希望绑定会localhost失败,就像在 Linux 中尝试相同时一样(我专门在 Ubuntu 上尝试过)。
OS X 上的行为对我来说很奇怪,因为客户端连接localhost在侦听所有接口时工作,但新服务器可以绑定localhost到同一端口并接受新连接,而不是第一个侦听器。
套接字如何侦听所有接口并防止其他套接字绑定到localhostOS X 上的相同端口?
以下测试在 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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试过的: