我是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地址获取国家代码和名称。
提前致谢!
最佳答案
您可以使用以下完美指南: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;
}