ip地址解析成国家、城市、iso code或者按语言获取城市名

通过使用免费geoip库,解析ip。github完整项目代码:https://github.com/luoqifei/user-location/tree/master/geoipdemo

学习GeoLite2 Free Downloadable Databases api :https://dev.maxmind.com/geoip/geoip2/geolite2/

java实现如下:

public class IpDemo {
    public static void main(String[] args) throws Exception {
        //city db demo,获取城市
        String basePath = IpDemo.class.getResource("./geoipdb").getPath();
        System.out.println(basePath);
        Geo cityGeo = new Geo(basePath+"/GeoLite2-City.mmdb");
        Geo countryGeo = new Geo(basePath+"/GeoLite2-Country.mmdb");

        String ip1= "211.145.63.25";
        System.out.printf("ip=%s,country=%s,city=%s\n",ip1,countryGeo.getCountryIsoCode(ip1),cityGeo.getCityName(ip1));
        String ip2= "114.114.114.114";
        System.out.printf("ip=%s,country=%s,city=%s\n",ip2,countryGeo.getCountryIsoCode(ip2),cityGeo.getCityName(ip2));
        /**out put
        ip=211.145.63.25,country=CN,city=Beijing
        ip=114.114.114.114,country=CN,city=Nanjing
        */
        //显示城市中文名、英文名
        System.out.printf("ip=%s, city_CN=%s",ip1,cityGeo.getCityNameByLanguageKey(ip1,"zh-CN"));
        System.out.printf("ip=%s, city_CN=%s",ip2,cityGeo.getCityNameByLanguageKey(ip2,"zh-CN"));
    }
}
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

public class Geo {

    private static final Logger logger = LoggerFactory.getLogger(Geo.class);

    private DatabaseReader reader;

    public Geo(String dbfile) throws Exception {
        if (dbfile == null) {
            throw new Exception("geo database must not be null!");
        }
        try {
            File db = new File(dbfile);
            logger.info(">>> db file path: {}", db.getAbsolutePath());
            reader = new DatabaseReader.Builder(db).withCache(new CHMCache()).build();
        } catch (IOException e) {
            throw new Exception(String.format("geo database [%s] may not exist!", dbfile));
        }
    }
    public String getCityName(String ip){
        if(ip != null){
            try {
                InetAddress ipAddress = InetAddress.getByName(ip);
                String databaseType = reader.getMetadata().getDatabaseType();
                City city = null;
                if (databaseType.contains("City")) {
                    city = reader.city(ipAddress).getCity();
                } else if (databaseType.contains("Country")) {
                    logger.error("Used a wrong db which is countryDB to get city.");
                    return null;
                }
                if (city != null && city.getName() != null) {
                    return city.getName();
                }
            } catch (IOException | GeoIp2Exception e) {
                logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());
            }

        }
        return "unKnown city";
    }

    /**
     * key = {de ru pt-BR,ja, en, fr, zh-CN, es}
     * @param ip
     * @return
     */
    public String getCityNameByLanguageKey(String ip,String language){
        if(ip != null){
            try {
                InetAddress ipAddress = InetAddress.getByName(ip);
                String databaseType = reader.getMetadata().getDatabaseType();
                City city = null;
                if (databaseType.contains("City")) {
                    city = reader.city(ipAddress).getCity();
                } else if (databaseType.contains("Country")) {
                    logger.error("Used a wrong db which is countryDB to get city.");
                    return null;
                }
                if (city != null && city.getName() != null) {
                    return city.getNames().get(language);
                }
            } catch (IOException | GeoIp2Exception e) {
                logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());
            }

        }
        return "unKnown city";
    }
    public String getCountryIsoCode(String ip) {
        return getCountryIsoCode(ip, null);
    }

    public boolean isFromChina(String ip){
        String code = getCountryIsoCode(ip);
        if(code != null){
            if(code.equals("CN")) {
                logger.info("check ip={}, result is CN",ip);
                return true;
            } else {
                logger.info("check ip={},result is not CN,but {}",ip,code);
                return false;
            }
        }else {//null set it as china
            logger.info("check ip={} , but the code is null,we set it as CN.",ip);
            return true;
        }
    }
    public String getCountryIsoCode(String ip, String defaultValue) {
        if (ip == null) {
            return defaultValue;
        }
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);
            String databaseType = reader.getMetadata().getDatabaseType();
            Country country = null;
            if (databaseType.contains("City")) {
                CityResponse response = reader.city(ipAddress);
                country = response.getCountry();
            } else if (databaseType.contains("Country")) {
                CountryResponse response = reader.country(ipAddress);
                country = response.getCountry();
            }
            if (country != null && country.getIsoCode() != null) {
                return country.getIsoCode().toUpperCase();
            } else {
                return defaultValue;
            }
        } catch (IOException | GeoIp2Exception e) {
            logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());
        }
        return defaultValue;
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值