安卓获取外网IP

标签 android ip external

<分区>

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

最佳答案

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

}

关于安卓获取外网IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077555/

相关文章:

linux - 在 Slackware 上通过 shellscript 更改 IP 地址

javascript - 将外部脚本中的 javascript 插入 HTML 中的 javascript

python - Pandas检查IP地址属于哪个子网

arrays - 从 C# 到 F# : Pinned Array and Stringbuilder in external function called from F#

c - 使用 DLL 调用 Modelica 外部 C 函数

java - 我无法在我的设备上运行该应用程序,错误类型为 3

android - 我需要多久调用一次 Parse.subscribeInBackground() 才能订阅 Parse 推送?

java - 我想将从字符串中获取的字符串传递给 onPostExecute 方法

java - 如何让android程序等待两个按钮被按下?

email - 使用IP地址而不是域名发送电子邮件