Android应用程序从网络获取IP地址

时间:2014-12-15 12:24:01

标签: android

我有一个带有表单的应用程序,在提交时会获取IP地址。不幸的是,应用程序从路由器获取ip,如192.168.1.4或有时甚至0.0.0.0

这是我使用的代码

String hostaddr="";
public String getLocalIpAddress() {
WifiManager wifiMan = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),            (ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
 return ip;
 }

我如何获得正确的IP地址?

1 个答案:

答案 0 :(得分:2)

您正在获取分配给手机网络接口的IP地址。如果您需要获取公共IP地址,则有两种选择:

(1)以某种方式查询路由器的默认网关并递归执行此操作,直到获得公共IP地址。

(2)连接到互联网上的某些服务,它会告诉您连接的IP地址。有很多服务可以做到这一点,例如:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://icanhazip.com/");
HttpResponse resp = client.execute(get);

InputStream content = resp.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String myIP = trim(buffer.readLine());
buffer.close();
content.close();

现在变量myIP将包含您的公共IP地址。当然,您需要添加异常处理。请注意,我还没有对此代码进行过测试,因此您可能需要对其进行一些小调试。