根据IP获取国家代码

pom.xml

<dependency>
	<groupId>com.maxmind.geoip2</groupId>
	<artifactId>geoip2</artifactId>
	<version>2.9.0</version>
</dependency>

示例

System.out.println(GeoIpUtils.getCountryName("113.116.217.190")); // China
System.out.println(GeoIpUtils.getCountryCode("113.116.217.190")); // CN

GeoIpUtils.java

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;

/** 
 * @Description: geoip工具类
 */ 
public class GeoIpUtils {
	
	private final static Logger logger = LoggerFactory.getLogger(GeoIpUtils.class);

	private static DatabaseReader reader;
	
	private static DatabaseReader getReader(){
		try{
			if(reader == null){
				logger.warn("打开ip数据库");
				File database =  new File(GeoIpUtils.class.getClassLoader().getResource("geoip/GeoLite2-Country.mmdb").getFile()); // 附件下载百度云地址https://pan.baidu.com/s/1ENqTeCoMIWJMbh88nYU5gg
				reader = new DatabaseReader.Builder(database).build();
			}
			return reader;
		}catch(Exception e){
			return reader;
		}
		
	}
	
	/**
	 * 根据ip获取国家对象,不存在则返回null
	 * @param ip
	 * @return
	 */
	public static Country getCountry(String ip){
		try{
			InetAddress ipAddress = InetAddress.getByName(ip);
			CountryResponse response = getReader().country(ipAddress);
			Country country = response.getCountry();
			return country;
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 根据ip获取国家代码,不存在则返回null
	 * @param ip
	 * @return
	 */
	public static String getCountryCode(String ip){
		Country country = getCountry(ip);
		return country != null ? country.getIsoCode() : null;
	}
	
	/**
	 * 根据ip获取国家名称,不存在则返回null
	 * @param ip
	 * @return
	 */
	public static String getCountryName(String ip){
		Country country = getCountry(ip);
		return country != null ? country.getName() : null;
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值