How To Get Ip Address In Java Using Inetaddress

An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. In Java, the InetAddress class represents an Internet Protocol (IP) address.

Here we will learn how to get localhost IP address and a website IP addresses in java using InetAddress.

package com.journaldev.util;import;import;public class JavaIPAddress { /** * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { //print localhost ip address System.out.println(InetAddress.getLocalHost().getHostAddress()); //print website ip address System.out.println(InetAddress.getByName("")); //print all ip addresses for a website InetAddress[] inetAddresses = InetAddress.getAllByName(""); for(InetAddress inet : inetAddresses){ System.out.println(inet); } }}

Output of the above program is:

When we use InetAddress.getByName(String host) it returns the current IPv4 address of the hostname, when we use InetAddress.getAllByName(String host) it returns all the IP addresses associated with the hostname. The last output of IP is IPv6 format IP address.

These methods throw UnknownHostException if there are no IP addresses associated with the hostname. Note that we should not use any protocol like HTTP to provide the hostname input.

  • 20