如何在Android应用程序上获取真实的IP地址?

时间:2016-09-05 17:49:33

标签: android ip

如何获取真实的IP地址? 我使用下面的代码,结果总是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();
}

3 个答案:

答案 0 :(得分: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;
}

来源https://stackoverflow.com/a/11432695/5284441

答案 1 :(得分:1)

您无法通过应用的api android获取公共IP地址。该方法是向某个网站发送请求,该网站将响应有关您的公共IP地址的信息,然后解析结果以获取公共IP。

答案 2 :(得分:0)

只需使用Volley从this网站获取IP

T(n) = O(n)