Friday 9 October 2015

InetAddress : Gets all address associated with hostname

One hostname (For example, google.com) can be associated with multiple IP address. InetAddress class provides getAllByName() method to get all the InetAddress associated with this IP.
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressUtil {

  public static InetAddress getByName(String hostName) {
    try {
      return InetAddress.getByName(hostName);
    } catch (UnknownHostException e) {
      System.out.println(e.getMessage());
    }
    return null;
  }
  
  public static String getHostName(String ip){
    InetAddress address = getByName(ip);
    return address.getHostName();
  }

  public static InetAddress[] getAllAddresses(String hostName){
    try {
      InetAddress[] addresses = InetAddress.getAllByName(hostName);
      return addresses;
    } catch (UnknownHostException e) {
      System.out.println(e.getMessage());
    }
    return null;
  }
}

import java.net.InetAddress;

public class Main {
  public static void main(String args[]) {   
    InetAddress[] addresses = InetAddressUtil.getAllAddresses("www.google.com");
    
    for(InetAddress addr : addresses){
      System.out.println(addr.getHostAddress());
    }
  }
}


Sample Output
64.233.169.103
64.233.169.147
64.233.169.99
64.233.169.105
64.233.169.104
64.233.169.106
2607:f8b0:4003:c08:0:0:0:69



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment