张利高 张利高 - 2 months ago 14
Android Question

How to get the real IP address on Android application?

How to get the real IP address ?
I use Code below, the result always be 127.0.0.1

if (getIpType(context) == IP_TYPE_WIFI) {

WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
WifiInfo wifiinfo = wifi_service.getConnectionInfo();
String ip = Formatter.formatIpAddress(dhcpInfo.ipAddress);

} else {

Runnable IpRunnable = new Runnable() {

@Override
public void run() {

InetAddress addr;
String localIp = null;

try {
addr = InetAddress.getLocalHost();
localIp = addr.getHostAddress();
} catch (UnknownHostException e) {
}
}
};

Thread payThread = new Thread(IpRunnable);
payThread.start();
}

Answer

Try this

public String getLocalIpAddress(){
   try {
       for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();  
       en.hasMoreElements();) {
       NetworkInterface intf = en.nextElement();
           for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
           InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                return inetAddress.getHostAddress().toString();
                }
           }
       }
       } catch (Exception ex) {
          Log.e("IP Address", ex.toString());
      }
      return null;
}

source http://stackoverflow.com/a/11432695/5284441

Comments