国家代码如何用ip地址?

时间:2016-06-23 06:28:38

标签: ios ip-address country-codes

我想知道带有IP地址的国家/地区代码。

不使用gps。

有可能吗?

2 个答案:

答案 0 :(得分:0)

我认为NSLocale是获取国家/地区代码和名称而不是IP的好选择,所以请尝试下面的代码:

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *countryName = [locale displayNameForKey: NSLocaleCountryCode value: countryCode];
NSLog(@"%@ %@",countryName, countryCode);

希望这对你有所帮助。

答案 1 :(得分:0)

您可以从http://lite.ip2location.com/database-ip-country

将IP下载到国家/地区数据库

要从IP范围中提取国家/地区,请不要忘记计算IP编号:

public Long getIpNumber(String ip) {

    if (StringUtils.isBlank(ip))
        return null;

    String[] ipArray = ip.split("\\.");

    long result = 0;
    long ipLong = 0;

    for (int x = 3; x >= 0; x--) {
        ipLong = Long.parseLong(ipArray[3 - x]);
        result |= ipLong << (x << 3);
    }

    return result;
}