get Host Address - Android java.net

Android examples for java.net:NetworkInterface

Description

get Host Address

Demo Code

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Locale;

import android.util.Log;

public class Main {

  private static final String TAG = "wifi-utils";

  /**/*from   ww w . j  a  va2s.co m*/
   * get local IP address/domain name for use in URLs by other machines on
   * network; most likely wireless
   * 
   * @return IP address (as string)
   */
  public static String getHostAddress() {
    NetworkInterface ni = getWifiInterface();
    return getHostAddress(ni);
  }

  public static String getHostAddress(NetworkInterface ni) {
    if (ni == null) {
      Log.w(TAG, "Could not find local interface - using loopback");
      return "127.0.0.1";
    }
    // IPv4 only for now?!
    Enumeration<InetAddress> ias = ni.getInetAddresses();
    while (ias.hasMoreElements()) {
      InetAddress addr = ias.nextElement();
      if (addr.isLoopbackAddress())
        continue;
      if (addr.isMulticastAddress())
        continue;
      if (addr instanceof Inet4Address) {
        return addr.getHostAddress();
      }
    }
    Log.w(TAG, "Could not find useful local IP address - using loopback");
    return "127.0.0.1";
  }

  public static NetworkInterface getWifiInterface() {
    Enumeration<NetworkInterface> nis;
    try {
      nis = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      Log.e(TAG, "getWifiInterface could not getNetworkInterfaces: " + e.getMessage(), e);
      return null;
    }
    LinkedList<NetworkInterface> bestnis = new LinkedList<NetworkInterface>();
    // order best?!
    while (nis.hasMoreElements()) {
      NetworkInterface ni = nis.nextElement();
      String name = ni.getName().toLowerCase(Locale.US);
      if (name.startsWith("lo")) {
        Log.d(TAG, "skip loopback interface " + name);
        continue;
      }
      if (name.startsWith("w"))
        bestnis.addFirst(ni);
      else
        bestnis.addLast(ni);
    }
    for (NetworkInterface ni : bestnis) {
      // IPv4 only for now?!
      Enumeration<InetAddress> ias = ni.getInetAddresses();
      while (ias.hasMoreElements()) {
        InetAddress addr = ias.nextElement();
        if (addr.isLoopbackAddress())
          continue;
        if (addr.isMulticastAddress())
          continue;
        if (addr instanceof Inet4Address) {
          return ni;
        }
      }
    }
    return null;

  }

}

Related Tutorials