Android获取外部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\");
    }

}
    ,http://api.externalip.net/ip将以简单的api格式返回您的ip 您可以在此处阅读有关获取外部IP的更多信息:http://www.externalip.net/api     ,我认为没有办法以编程方式进行操作,但是您可以调用http://www.whatismyip.com/这样的网站,然后从页面中删除IP。您可能想找到一个提供API并支持第三方调用的站点。     ,看一下以下代码片段:
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);
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...