get Local Ip Address - Android java.net

Android examples for java.net:IP Address

Description

get Local Ip Address

Demo Code

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

public class Main {

  public static String getLocalIpAddress(String remoteIpAddress) {

    Enumeration<NetworkInterface> en = null;

    try {/* w w  w. ja  v a 2 s.c  o m*/
      en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      e.printStackTrace();
      return null;
    }

    while (en.hasMoreElements()) {

      NetworkInterface nif = en.nextElement();
      Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();

      while (enumIpAddr.hasMoreElements()) {

        InetAddress inetAddress = enumIpAddr.nextElement();

        if (inetAddress.isLoopbackAddress())
          continue;

        if (!(inetAddress instanceof Inet4Address))
          continue;

        String ip = inetAddress.getHostAddress().toString();

        if (remoteIpAddress == null)
          return ip;

        String[] localIp = ip.split("\\.");
        String[] remoteIp = remoteIpAddress.split("\\.");
        if (localIp.length != 4 || remoteIp.length != 4)
          return ip;

        if (localIp[0].equals(remoteIp[0]) && localIp[1].equals(remoteIp[1]) && localIp[2].equals(remoteIp[2]))
          return ip;
      }
    }

    return null;
  }

}

Related Tutorials