简体   繁体   English

如何创建仅限localhost的Java套接字?

[英]How to create Java socket that is localhost only?

I have a Java server that opens up a socket using ServerSocket (using Thrift with it). 我有一个Java服务器,使用ServerSocket打开一个套接字(使用Thrift)。 This server has a client on the local machine in Obj-c that communicates with the Java server. 该服务器在Obj-c中的本地机器上有一个客户端,它与Java服务器通信。 Everything happens on localhost. 一切都发生在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. 现在java服务器在网络上也是可见的,我希望java服务器只能在localhost上访问。 Otherwise it is a potential security vulnerability and it freaks users out when their firewall warns them. 否则,这是一个潜在的安全漏洞,当防火墙警告他们时,它会吓跑用户。

I tried creating the server socket using an InetSocketAddress('localhost', 9090) but that seems to have no effect. 我尝试使用InetSocketAddress('localhost',9090)创建服务器套接字,但似乎没有任何效果。 How can I limit this thing to localhost? 我怎样才能将这个东西限制在localhost?

Taken from another question: 取自另一个问题:

new ServerSocket(9090, 0, InetAddress.getByName(null));

InetAddress.getByName(null) points to the loopback address (127.0.0.1) InetAddress.getByName(null)指向环回地址(127.0.0.1)

And here's the Javadoc where it says that 这就是 Javadoc所说的

Try 尝试

new ServerSocket(9090, 0, InetAddress.getByName("localhost"))

The last parameter to the constructor specifies which address to bind the listening socket to. 构造函数的最后一个参数指定将侦听套接字绑定到的地址。

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. 所有其他“localhost”解决方案将使Java选择一个接口。

new ServerSocket(9090, 0, InetAddress.getLoopbackAddress());

This is available since Java 7, and does not even throw UnknownHostException 这是从Java 7开始提供的,甚至不会抛出UnknownHostException

new ServerSocket(9090, 0, InetAddress.getByName(null));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM