Search code examples
javanetwork-programmingrmi

RMI Server uses wrong IP address


I am starting my RMI server while my network card is connected to Network A. Running my client succeeds as expected and prints "Hello World". As soon as I change my Network connection to Network B (without restarting my RMI server!) I am not able to connect to the server anymore. Server and client always run on the same host, so using localhost address would be sufficient.

Server:

public class HelloImpl extends UnicastRemoteObject implements Hello {

    public HelloImpl() throws RemoteException {
    }

    public String sayHello() {
        return "Hello world!";
    }

    public static void main(String args[]) throws RemoteException {
        Registry registry = LocateRegistry.createRegistry(3128);
        registry.rebind("HelloServer", new HelloImpl());
    }
}

Client:

public class HelloClient {

    public static void main(String arg[]) throws Exception{
        Registry registry=LocateRegistry.getRegistry("localhost", 3128);;
        Hello result = (Hello) registry.lookup("HelloServer");
        System.out.println(result.sayHello());
    }

}

Exception is:

HelloClient exception: Connection refused to host: 192.168.169.136; nested exception is: 
    java.net.ConnectException: Connection timed out: connect

Which refers to my IP address that was assigned while being connected to Network A. There Registry lookup works as expected, only the call to result.sayHello() fails with the exception above.

How to tell RMI to use localhost for everything (and not only the registry)?


Solution

  • Set the system property java.rmi,server.hostname to 127.0.0.1 at the server JVM, before exporting any remote objects, including the Registry.