Java IP地址解析工具ip2region,什么是ip2region?
ip2region – 准确率99.9%的离线IP地址定位库,0.0x毫秒级查询,ip2region.db数据库只有数MB,提供了java,php,c,python,nodejs,golang,c#等查询绑定和Binary,B-tree,内存三种查询算法。
实现的基本流程:
一、导入依赖:
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
工程的所有依赖 (xml文件内代码,没什么用):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>Ipsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Ipsearch</name>
<description>Ipsearch</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- ip2region -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.12 </version>
</plugin>
</plugins>
</build>
</project>
二、下载ip2region.db文件:
下载后将文件放到resources文件夹下:
三、配置一个工具类IPUtil,代码如下:
package com.example.ipsearch.Sutil;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
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) {
URL url = IPUtil.class.getClassLoader().getResource("ip2region.db");
File file;
if (url != null) {
file = new File(url.getFile());
} else {
return null;
}
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;
}
}
四、调用方法:
只调用类中的第二个方法即可实现ip地址向所属地的转化:
System.out.println(IPUtil.getCityInfo("ip"));
这里把”ip”换成具体的ip地址,运行即可实现单个ip地址转化为所属地的输出。
若想输出上万个ip的所属地,可以把ip全部放到txt文件里,通过BufferedReader类中的方法读取txt文件中的ip,存到Arraylist中 用循环全部输出,具体代码如下:
package com.example.ipsearch;
import com.example.ipsearch.Sutil.IPUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class IpsearchApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(IpsearchApplication.class, args);
File a=new File("E:\\test.txt");
FileReader b = null; // 创建FileInputStream类对象读取File
BufferedReader c = null; // 创建reader缓冲区将文件流装进去
b = new FileReader(a);
c = new BufferedReader(b);
String e=null;
List <String> f=new ArrayList<>();
while ((e=c.readLine())!=null)
{
f.add(e);
}
b.close();
c.close();
for(String f1:f)
{
System.out.println(IPUtil.getCityInfo(f1));
}
};
}
五、工程框架结构及运行结果展示:
版权声明:本文为qq_52506111原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。