问题描述
|
这个问题已经在这里有了答案:
解决方法
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);