IP Address

In this chapter you will learn:

  1. Get IP address for local host
  2. Get Host name from InetAddress
  3. Getting the IP Address of a Hostname
  4. Get all IP addresses
  5. Compare two InetAddresses

IP address for local host

import java.net.InetAddress;
/*from j  a v a 2 s . c  o  m*/
public class MainClass {

  public static void main(String[] args) {

    try {
      InetAddress me = InetAddress.getLocalHost();
      String dottedQuad = me.getHostAddress();
      System.out.println("My address is " + dottedQuad);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

The code above generates the following result.

Get Host name from InetAddress

import java.net.InetAddress; import java.net.UnknownHostException; public class Main{ public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println("My name is " + address.getHostName()); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own name."); } } }

Getting the IP Address of a Hostname

import java.net.InetAddress;
// ja va 2 s. com
public class Main {
  public static void main(String[] argv) throws Exception {
    InetAddress addr = InetAddress.getByName("www.google.com");
    System.out.println(addr.getHostAddress());

    
  }
}

The code above generates the following result.

Get all IP addresses

Get all IP address for a host name.

import java.net.InetAddress;
/*from   j  ava  2  s .  co m*/
public class Main {

  public static void main(String[] args) throws Exception {

    InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
    for (int i = 0; i < addresses.length; i++) {
      System.out.println(addresses[i]);
    }

  }

}

The code above generates the following result.

Compare two InetAddresses

import java.net.InetAddress;
// j a  v  a 2 s . co m
public class MainClass {

  public static void main(String args[]) throws Exception {

    InetAddress ca = InetAddress.getByName("www.google.ca");
    InetAddress com = InetAddress.getByName("www.google.com");
    if (ca.equals(com)) {
      System.out.println("same");
    } else {
      System.out.println("not the same");
    }
  }

}

Next chapter...

What you will learn in the next chapter:

  1. How to ping an IP address
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface