Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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?

like image 674
Matt Ronge Avatar asked Feb 05 '10 04:02

Matt Ronge


People also ask

What are the three types of sockets in java?

Java provides three different types of sockets. Connection-oriented (TCP) sockets are implemented with the Socket class. Connectionless (UDP) sockets use the Datagramsocket class. A third type is the Multicastsocket class, which is a subclass of the DatagramSocket class.

What is localhost in java?

The getLocalHost() method of Java InetAddress class returns the instance of InetAddress containing local host name and address. In this, firstly the host name is retrieved from the system, then that name is resolved into InetAddress.


4 Answers

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

like image 43
Fabian Lange Avatar answered Sep 21 '22 05:09

Fabian Lange


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

like image 63
Tute Avatar answered Sep 21 '22 05:09

Tute


Try

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

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

like image 42
Geoff Reedy Avatar answered Sep 21 '22 05:09

Geoff Reedy


new ServerSocket(9090, 0, InetAddress.getByName(null));
like image 33
user207421 Avatar answered Sep 21 '22 05:09

user207421