如何创建仅限本地主机的 Java 套接字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2205073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create Java socket that is localhost only?
提问by Matt Ronge
I have a Java server that opens up a socket using ServerSocket (using Thrift with it). This server has a client on the local machine in Obj-c that communicates with the Java server. Everything happens on localhost. Right now the java server is visible on the network as well, I would like the java server to only be accessible on localhost. Otherwise it is a potential security vulnerability and it freaks users out when their firewall warns them.
我有一个 Java 服务器,它使用 ServerSocket(使用 Thrift)打开一个套接字。该服务器在 Obj-c 中的本地机器上有一个客户端,它与 Java 服务器进行通信。一切都发生在本地主机上。现在java服务器在网络上也是可见的,我希望java服务器只能在本地主机上访问。否则,这是一个潜在的安全漏洞,当他们的防火墙警告用户时,它会吓坏用户。
I tried creating the server socket using an InetSocketAddress('localhost', 9090) but that seems to have no effect. How can I limit this thing to localhost?
我尝试使用 InetSocketAddress('localhost', 9090) 创建服务器套接字,但这似乎没有效果。我怎样才能把这个东西限制在本地主机上?
回答by Geoff Reedy
Try
尝试
new ServerSocket(9090, 0, InetAddress.getByName("localhost"))
The last parameter to the constructor specifies which address to bind the listening socket to.
构造函数的最后一个参数指定将侦听套接字绑定到哪个地址。
回答by user207421
new ServerSocket(9090, 0, InetAddress.getByName(null));
回答by Matías
回答by Fabian Lange
Let me chime in with an alternative solution which only accepts on loopback device. All the other "localhost" solutions will make Java pick an interface.
让我提出一个仅在环回设备上接受的替代解决方案。所有其他“本地主机”解决方案将使 Java 选择一个接口。
new ServerSocket(9090, 0, InetAddress.getLoopbackAddress());
This is available since Java 7, and does not even throw UnknownHostException
这是自 Java 7 以来可用的,甚至不会抛出 UnknownHostException