Here we will learn how to get localhost IP address and a website IP addresses in java using InetAddress.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.journaldev.util; import java.net.UnknownHostException; import java.net.InetAddress; 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("www.journaldev.com")); //print all ip addresses for a website InetAddress[] inetAddresses = InetAddress.getAllByName("www.google.com"); for(InetAddress inet : inetAddresses){ System.out.println(inet); } } } |
Output of the above program is:
1 2 3 4 5 6 7 8 9 10 |
<span style="color: #008000;"><strong><code> 192.168.3.1 www.journaldev.com/50.116.65.160 www.google.com/74.125.224.82 www.google.com/74.125.224.81 www.google.com/74.125.224.80 www.google.com/74.125.224.83 www.google.com/74.125.224.84 www.google.com/2001:4860:4001:803:0:0:0:1010 </code></strong></span> |
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 google.com 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.