How do I ping a host?

Since Java 1.5 (Tiger) the java.net.InetAddress class introduces isReachable() method that can be use to ping or check if the address specified by the InetAddress is reachable.

package org.kodejava.example.net;

import java.net.InetAddress;

public class PingExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getByName("172.16.2.0");

            // Try to reach the specified address within the timeout
            // period. If during this period the address cannot be
            // reach then the method returns false.
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I get a localhost hostname?

package org.kodejava.example.net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class HostnameExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getLocalHost();

            System.out.println("Hostname: " + address.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

How do I get IP address of localhost?

The example here show you how to get an IP or host address using the java.net.InetAddress class. To get an instance of InetAddress we call a static method of this class, the method is getLocalHost(), which return the local host address. Next, to get the IP address we can call the getHostAddress() method.

package org.kodejava.example.net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddressExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();

            System.out.println("IP Address = " + ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

The result of this code snippet:

IP Address = 192.168.1.64