Search code examples
javaserverclientclient-serverserversocket

Find server ip address on local network


I wrote a simple server-client software that runs on a local network /24 (255.255.255.0)and I don't know how to find the ip address when it changes.

  • The ip address of the server is not static.

  • I can't save the mac address and then retrieve the ip address from the arp table because it will run on different machines.

The only way for clients to find the correct ip address is to try the whole range until the connection gets accepted?


Solution

  • You could use the hostname of the server instead of the IP. When IP changes the hostname should stay the same.

    You can establish the hostname in many ways. Either programmatically:

     String hostName = InetAddress.getLocalHost().getHostName();
    

    Or with an OS command or a tool.

    For example, on Windows it could be

    ipconfig /all
    

    On Linux it could probably be

    hostname
    

    or

    hostnamectl
    

    Once you know the hostname you could use it to establish a connection. Alternatively, you could also get the IP of the server programmatically on any client in the local network. In Java you could use the following code:

    InetAddress.getByName("serverHostName").getHostAddress()