如何获取真实 IP address 的 Android application ?

标签: Android
发布时间: 2016/10/10 20:10:37
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

如何获取真实 IP address 吗? 我用下面的代码,结果永远是 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();
}

解决方法 1:

试试这个

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

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

赞助商