我是新的android,我想获得国家名称和国家代码使用ip地址。请任何人指导我。
获取IP的代码如下:
public String getLocalIpAddress() {
WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(context.WIFI_SERVICE);
if(wifiMgr.isWifiEnabled()) {
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String wifiIpAddress = String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return wifiIpAddress;
}else{
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();
Log.i("","111 inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
//the condition after && is missing in your snippet, checking instance of inetAddress
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
Log.i("","111 return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
return null;
}我不知道如何使用IP地址获取国家代码和名称。
提前感谢!
发布于 2016-08-30 00:35:55
1.)查询您的公网ip地址:
public static String getPublicIP() throws IOException
{
Document doc = Jsoup.connect("http://www.checkip.org").get();
return doc.getElementById("yourip").select("h1").first().select("span").text();
}2.)然后查询您的国家代码/名称:(使用上面的方法)
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://ipinfo.io/"+getPublicIP());
HttpResponse response;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}我希望这能帮到你。
发布于 2016-08-29 20:56:22
你可以使用这个完美的指南:http://www.mkyong.com/java/java-find-location-using-ip-address/
//ip address something like that 192.168.0.1
public String getCountryFromIP(String ipAddress) {
File file = new File("resources/GeoLiteCity.dat");
LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
Location locationServices = lookup.getLocation(ipAddress);
return locationServices.countryName;
}发布于 2016-08-30 00:00:54
首先,您应该获取设备的外部IP地址,然后使用一些web API like this来获取国家代码和名称。
https://stackoverflow.com/questions/39206727
复制相似问题