get My Ip Address - Android java.net

Android examples for java.net:IP Address

Description

get My Ip Address

Demo Code

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteOrder;

import android.net.wifi.WifiManager;
import android.util.Log;

public class Main {

  public static String getMyIpAddress(WifiManager w) {
    return ipAddressToString(w.getConnectionInfo().getIpAddress());
  }//  w  w w.j a  v  a2 s  . co  m

  public static String ipAddressToString(int ipAddress) {

    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
      ipAddress = Integer.reverseBytes(ipAddress);
    }

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

    String ipAddressString;
    try {
      ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
      Log.e("WIFI_IP", "Unable to get host address.");
      ipAddressString = "NaN";
    }

    return ipAddressString;
  }

}

Related Tutorials