Search code examples
javalocalhostrestrictjava-websocket

Restrict java-websocket access to localhost


I'm writing a java-websocket server as a cryptocurrency client.

For security reasons, I'd like to restrict access to the local machine.

Is there a way to restrict access to a java-websocket server by IP or hostname?

If so, how?


Solution

  • You should specify your listening ip to 127.0.0.1 thus it wont be possible to connect from the outside.

    Edit

    Looking at the example ChatServer.java the binding happens with

    ChatServer s = new ChatServer( port );
    

    The class implements two constructors:

      public ChatServer( int port ) throws UnknownHostException {
                super( new InetSocketAddress( port ) );
        }
    
        public ChatServer( InetSocketAddress address ) {
                super( address );
        }
    

    So you could also call the server with an inetSocketAddress. Create one thats binds to localhost:

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

    and then call the server with that instead of just the port.

    So replace

    ChatServer s = new ChatServer( port );
    

    with

    InetSocketAddress myLocalSocket = new ServerSocket(9090, 0, InetAddress.getByName(null));
    ChatServer s = new ChatServer( myLocalSocket );
    

    in your example and it should work.