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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.