【问题标题】:Android get external IP [duplicate]Android获取外部IP [重复]
【发布时间】:2011-08-29 23:18:58
【问题描述】:

我正在 android 2.1 中开发一个应用程序,我想显示外部 IP。我怎么能这样做?提前致谢。

【问题讨论】:

  • 您认为什么是“外部”IP 地址?

标签: android ip external


【解决方案1】:
public void getCurrentIP () {
    ip.setText("Please wait...");  
    try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://ifcfg.me/ip");
            // HttpGet httpget = new HttpGet("http://ipecho.net/plain");
            HttpResponse response;

            response = httpclient.execute(httpget);

            //Log.i("externalip",response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                    long len = entity.getContentLength();
                    if (len != -1 && len < 1024) {
                            String str=EntityUtils.toString(entity);
                            //Log.i("externalip",str);
                ip.setText(str);
                    } else {
                            ip.setText("Response too long or error.");
                            //debug
                            //ip.setText("Response too long or error: "+EntityUtils.toString(entity));
                            //Log.i("externalip",EntityUtils.toString(entity));
                    }            
            } else {
                    ip.setText("Null:"+response.getStatusLine().toString());
            }

    }
    catch (Exception e)
    {
        ip.setText("Error");
    }

}

【讨论】:

【解决方案2】:

http://api.externalip.net/ip 将以简单的 api 格式返回您的 ip

您可以在此处阅读有关获取外部 ip 的更多信息:http://www.externalip.net/api

【讨论】:

    【解决方案3】:

    我认为没有办法以编程方式执行此操作,但您可以调用 http://www.whatismyip.com/ 之类的站点,然后从页面中删除 IP。您可能希望找到一个提供 API 并支持 3rd 方调用的网站。

    【讨论】:

      【解决方案4】:

      看看这段代码sn-p:

      String ipAddress = null;
          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()) {
                          ipAddress = inetAddress.getHostAddress().toString();
                      }
                  }
              }
          } catch (SocketException ex) {
              ex.printStackTrace();
          }
      
          Log.e("IP ADDRESS:", ipAddress);
      

      【讨论】:

      • 获取本地 IP 而不是外部 IP
      猜你喜欢
      • 2013-08-04
      • 2020-01-08
      • 2011-06-29
      • 2021-11-20
      • 2013-04-03
      • 2016-03-10
      • 1970-01-01
      • 2011-03-16
      相关资源
      最近更新 更多