Search code examples
javasocketsnetwork-programmingclient-serverprotocols

How to allow connections to a socket only within the same host in java


I have a use-case where I want to open a socket and allow connections that are coming only from the same host/machine in which the socket is opened. I don't want to allow any connections from other hosts.

Basically, I want to simulate VM protocol concept of Apache ActiveMQ which works on port 61616.

I want to create something like this:

Socket socket = new Socket("127.0.0.1", 5000)

Is there a way we can do this in Java? Or is there any workaround for this?


Solution

  • Simply create a ServerSocket that is bound to 127.0.0.1 for IPv4 or ::1 for IPv6. Only clients on the localhost will be able to connect to it.