Ip2Region有中文和数据结构支持,是一个很好的第三方ip转换工具。
java:
<dependency> <groupId>org.lionsoul</groupId> <artifactId>ip2region</artifactId> <version>1.7</version> </dependency>
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
public class Ip2Region {
public static void main(String[] args) throws Exception {
// ip
String ip = "121.33.59.18";
// 判断是否为IP地址 (可用)
//boolean isIpAddress = Util.isIpAddress(ip);
// ip和long互转 (可用)
// long ipLong = Util.ip2long(ip);
// String strIp = Util.long2ip(ipLong);
// 根据ip进行位置信息搜索
DbConfig config = new DbConfig();
// 获取ip库的位置(放在src下)(直接通过测试类获取文件Ip2RegionTest为测试类)
String dbfile = Ip2Region.class.getResource("/ip2region.db").getPath(); //获取src/java/resources路径下ip2region.db文件地址
DbSearcher searcher = new DbSearcher(config, dbfile);
// 采用Btree搜索
DataBlock block = searcher.btreeSearch(ip);
// 打印位置信息(格式:国家|大区|省份|城市|运营商)
System.out.println(block.getRegion());
}
}
scala:
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7</version>
</dependency>
import org.junit.Test
import org.lionsoul.ip2region.{DataBlock, DbConfig, DbSearcher}
class IPTest {
/**
* IP -> Region, City
*/
@Test
def ip2Region(): Unit = {
val searcher = new DbSearcher(new DbConfig(), "dataset/ip2region.db")
val region = searcher.btreeSearch("121.33.59.18").getRegion
println(region)
}
}
地址:https://pan.baidu.com/s/13W7EFg-GiBVkMjNdl-a5RA
密码:0wi6