【发布时间】:2011-08-29 23:18:58
【问题描述】:
我正在 android 2.1 中开发一个应用程序,我想显示外部 IP。我怎么能这样做?提前致谢。
【问题讨论】:
-
您认为什么是“外部”IP 地址?
我正在 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");
}
}
【讨论】:
http://api.externalip.net/ip 将以简单的 api 格式返回您的 ip
您可以在此处阅读有关获取外部 ip 的更多信息:http://www.externalip.net/api
【讨论】:
我认为没有办法以编程方式执行此操作,但您可以调用 http://www.whatismyip.com/ 之类的站点,然后从页面中删除 IP。您可能希望找到一个提供 API 并支持 3rd 方调用的网站。
【讨论】:
看看这段代码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);
【讨论】: