Java InetAddress Class


The InetAddress class from the java.net package serves as a representation for both IPv4 and IPv6 addresses in Java. It provides methods to:

 

  • Get the IP address of a hostname
  • Get the hostname from an IP address
  • Work with local host/network details

notepad

The InetAddress class forms an indispensable part of DNS lookup and IP address management within Java networking


Creating InetAddress Objects

Get IP Address by Hostname

InetAddress address = InetAddress.getByName("www.google.com");
 

Get Local Host IP

 InetAddress localhost = InetAddress.getLocalHost();

Get All IPs (Multihomed host)

InetAddress[] addresses = InetAddress.getAllByName("www.microsoft.com");
 

Methods in InetAddress

Method Description
getByName(String host) Returns InetAddress for a hostname or IP string
getAllByName(String host) Returns all associated IPs
getHostAddress() Returns the IP address as a string
getHostName() Returns the host name
getLocalHost() Returns the address of the local machine
isReachable(int timeout) Checks if address is reachable

Example

Hostname to IP

 import java.net.*;

public class HostnameToIP {
    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getByName("www.google.com");
        System.out.println("Host: " + address.getHostName());
        System.out.println("IP Address: " + address.getHostAddress());
    }
}

Example

IP to Hostname

import java.net.*;

public class IPToHostname {
    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getByName("142.250.182.4");
        System.out.println("Host Name: " + address.getHostName());
    }
}

Example

Get Local Host Info

import java.net.*;

public class LocalHostInfo {
    public static void main(String[] args) throws Exception {
        InetAddress local = InetAddress.getLocalHost();
        System.out.println("Local Host Name: " + local.getHostName());
        System.out.println("Local IP Address: " + local.getHostAddress());
    }
}

Example

Check Reachability

InetAddress address = InetAddress.getByName("www.example.com");
if (address.isReachable(2000)) {
    System.out.println("Host is reachable");
} else {
    System.out.println("Host is NOT reachable");
}




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.