Mac OS X-将服务器套接字端口绑定到所有接口,并防止使用同一端口进行其他绑定

问题描述

在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());
        }
    }
}

我尝试过的事情:

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)