How to create Java socket that is localhost only?

2019-01-13 20:11发布

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.

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?

4条回答
SAY GOODBYE
2楼-- · 2019-01-13 20:53

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.

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

This is available since Java 7, and does not even throw UnknownHostException

查看更多
等我变得足够好
3楼-- · 2019-01-13 21:01

Try

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

The last parameter to the constructor specifies which address to bind the listening socket to.

查看更多
女痞
4楼-- · 2019-01-13 21:07
new ServerSocket(9090, 0, InetAddress.getByName(null));
查看更多
叛逆
5楼-- · 2019-01-13 21:12

Taken from another question:

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

InetAddress.getByName(null) points to the loopback address (127.0.0.1)

And here's the Javadoc where it says that

查看更多
登录 后发表回答