问题
i am trying to get the Internet Ip Address in my mobile. no need for device ip address. that device is connected with wifi or 3g or 2g or anyway. that mobile is having internet facility means, i need that internet IP Address.
Note : already i tried some coding. that code will work to get the device ip address only.
my prev code :
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())
{ return inetAddress.getHostAddress().toString(); }
}
}
}
catch (SocketException ex)
{
Log.e("ServerActivity", ex.toString());
}
Another one code :
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
Log.v("hari", "ipAddress:"+ipAddress);
Thanks Advance please any one help me..
回答1:
You can use this website and their API to get it: http://www.externalip.net/
Specifically http://api.externalip.net/ip
Alternatively (as mentioned by someone in the comments) you could create a PHP file on your server:
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
Android code using the externalip.net url (adapted from this answer)
HttpGet httppost = new HttpGet("http://api.externalip.net/ip");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String ipaddress = r.readLine();
来源:https://stackoverflow.com/questions/18918161/find-internet-ip-address-in-android-mobile-programmatically-no-need-device-ip