Java如何根据根据IP地址获取省市
作者:一名技术极客
这篇文章主要为大家详细介绍了两种在Java中获取IP地址对应地理位置信息的方法,分别是使用ip2region库和GeoIP库,感兴趣的小伙伴可以了解下
本文介绍了两种在Java中获取IP地址对应地理位置信息的方法。第一种是使用ip2region库,它提供毫秒级查询且数据库小巧,适合快速定位。第二种是利用GeoIP库,基于GeoLite数据库,可以获取到城市级别的信息。两种方法各有特点,适用于不同的场景需求。在选择方案时,需要考虑精度、速度和维护成本等因素。
方案一
最近要做一个埋点的功能,需求里要求记录用户登录的IP和地点,打算利用ip2region.db实现
首先下载ip2region.db
地址:下载地址
导入依赖
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
工具类
public class IPUtil {
/**
* 获取IP地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
if (ip.split(",").length > 1) {
ip = ip.split(",")[0];
}
return ip;
}
/**
* 根据IP地址获取城市
* @param ip
* @return
*/
public static String getCityInfo(String ip) throws IOException {
URL url = IPUtil.class.getResource("/ip2region.db");
File file;
file = new File("/app/project/croot_rims/package/webserver/ip2region.db");
if (!file.exists()) {
System.out.println("Error: Invalid ip2region.db file, filePath:" + file.getPath());
return null;
}
//查询算法
int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//DbSearcher.BINARY_ALGORITHM //Binary
//DbSearcher.MEMORY_ALGORITYM //Memory
try {
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method;
switch ( algorithm )
{
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
default:
return null;
}
DataBlock dataBlock;
if (!Util.isIpAddress(ip)) {
System.out.println("Error: Invalid ip address");
return null;
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
具体使用
String detail = IpUtils.getCityInfo("113.115.178.39");
方案二
在Java中,我们可以使用第三方库,例如GeoIP来获取IP地址所对应的地理位置信息。这个库是基于MaxMind的GeoLite数据库,它包含了大量的IP地址和相应的地理位置信息。
首先,你需要下载GeoLite数据库(这是一个.dat文件),然后将其放在你的项目的某个位置。接下来,你可以编写一个函数来查询这个数据库并获取IP地址的地理位置信息。
以下是一个简单的示例:
public class GeoIPTest {
public static void main(String[] args) throws IOException, GeoIp2Exception {
String ipAddress = "你的IP地址"; // 替换成你要查询的IP地址
File database = new File("你的数据库文件路径"); // 替换成你的GeoLite数据库文件路径
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
InetAddress ip = InetAddress.getByName(ipAddress);
CityResponse response = dbReader.city(ip);
City city = response.getCity();
System.out.println(city.getName()); // 输出城市名
}
}
注意:这个例子只能获取到城市级别的信息,如果你需要更详细的信息(比如具体的经纬度),你可以查看CityResponse对象的其他方法。
最后,别忘了将这个库添加到你的项目依赖中。如果你使用的是Maven,你可以在你的pom.xml文件中添加以下依赖:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.12.0</version> <!-- 请检查最新版本 -->
</dependency>到此这篇关于Java如何根据根据IP地址获取省市的文章就介绍到这了,更多相关Java IP地址获取省市内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
