Java get hostname and IP address

Use java.net.InetAddress to get hostname or IP Address

To get local hostname or IP

import java.net.InetAddress;

public class LocalIPGetter {
    public static void main(String[] args) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();

        // Get Hostname
        System.out.println(inetAddress.getHostName());

        // Get IP Address
        System.out.println(inetAddress.getHostAddress());
    }
}
$javac LocalIPGetter.java
$java LocalIPGetter
mytestpc
172.17.0.2

To get remote hostname or IP

import java.net.InetAddress;

public class RemoteIPGetter {
    public static void main(String[] args) throws Exception {
        InetAddress inetAddress = InetAddress.getByName("www.google.com");

        // Get Hostname
        System.out.println(inetAddress.getHostName());

        // Get IP Address
        System.out.println(inetAddress.getHostAddress());

        inetAddress = InetAddress.getByName("216.58.206.4");

        // Get Hostname
        System.out.println(inetAddress.getHostName());

        // Get IP Address
        System.out.println(inetAddress.getHostAddress());
    }
}
$javac RemoteIPGetter.java
$java RemoteIPGetter
www.google.com
216.58.206.4
fra16s20-in-f4.1e100.net
216.58.206.4