JAVA解析IPアドレス
16327 ワード
POMファイル
まとめ:
ip 2 region.dbダウンロードアドレス:
https://github.com/lionsoul2014/ip2region.git
テスト結果:
作者:pxj(潘陳)日付:2020-02-12午前1:25:30
4.0.0
com.ccj.pxj.ip
IpTets
1.0-SNAPSHOT
org.lionsoul
ip2region
1.7.2
package com.ccj.pxj;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import java.io.File;
import java.lang.reflect.Method;
public class JobIPUtil {
public static String parseIP(String ip){
//db
String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
File file = new File(dbPath);
if ( file.exists() == false ) {
System.out.println("Error: Invalid ip2region.db file");
}
//
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, dbPath);
//define the method
Method method = null;
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;
}
DataBlock dataBlock = null;
if ( Util.isIpAddress(ip) == false ) {
System.out.println("Error: Invalid ip address");
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
String IP = dataBlock.getRegion();
StringBuilder sb = new StringBuilder(IP);
sb.replace(IP.indexOf("|")+1,(IP.indexOf("|",IP.indexOf("|")+1)),"-");
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
// ( : | | | | )
System.out.println(parseIP("171.15.58.181"));
}
}
まとめ:
StringBuilder sb = new StringBuilder(IP);
sb.replace(IP.indexOf("|")+1,(IP.indexOf("|",IP.indexOf("|")+1)),"-");//
IP.indexOf("|")+1,(IP.indexOf("|",IP.indexOf("|")+1);//
ip 2 region.dbダウンロードアドレス:
https://github.com/lionsoul2014/ip2region.git
テスト結果:
|-| | |
作者:pxj(潘陳)日付:2020-02-12午前1:25:30