Friday, 9 October 2015

InetAddress object for local host

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;
  }

  public static InetAddress getLocalHost() {
    try {
      return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
      System.out.println(e.getMessage());
    }
    return null;
  }
}


import java.net.InetAddress;

public class Main {
  public static void main(String args[]) {
    InetAddress address = InetAddressUtil.getLocalHost();
    System.out.println(address);
  }
}

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment