該工具類以讀取本地純真IP地址庫實現,缺點不易更新
IPSeekerUtil.java 工具類
package com.gfan.yyq.yyqs.utils;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import com.gfan.yyq.yyqs.service.impl.IpServiceImpl;
/**
* * 用來讀取QQwry.dat文件,以根據ip獲得好友位置,QQwry.dat的格式是
* 一. 文件頭,共8字節
* 1. 第一個起始IP的絕對偏移, 4字節
* 2. 最後一個起始IP的絕對偏移, 4字節
* 二. "結束地址/國家/區域"記錄區 四字節ip地址後跟的每一條記錄分成兩個部分
* 1. 國家記錄
* 2.地區記錄 但是地區記錄是不一定有的。
* 三.而且國家記錄和地區記錄都有兩種形式
* 1. 以0結束的字符串
* 2. 4個字節,一個字節可能爲0x1或0x2
* a.爲0x1時,表示在絕對偏移後還跟着一個區域的記錄,注意是絕對偏移之後,而不是這四個字節之後
* b. 爲0x2時,表示在絕對偏移後沒有區域記錄
* 不管爲0x1還是0x2,後三個字節都是實際國家名的文件內絕對偏移
* 如果是地區記錄,0x1和0x2的含義不明,但是如果出現這兩個字節,也肯定是跟着3個字節偏移,如果不是 則爲0結尾字符串
* 四.起始地址/結束地址偏移"記錄區
* 1. 每條記錄7字節,按照起始地址從小到大排列
* a. 起始IP地址,4字節
* b. 結束ip地址的絕對偏移,3字節
*
* 注意,這個文件裏的ip地址和所有的偏移量均採用little-endian格式,而java是採用 big-endian格式的,要注意轉換
*
*/
public class IPSeekerUtil {
private Log log = LogFactory.getLog(IPSeekerUtil.class);
private static final int IP_RECORD_LENGTH = 7;
private static final byte AREA_FOLLOWED = 0x01;
private static final byte NO_AREA = 0x2;
private MappedByteBuffer buffer; // 內存映射文件,提高IO 讀取效率
private HashMap<String, IPLocation> cache = new HashMap<String, IPLocation>(); // 用來做爲cache,查詢一個ip時首先查看cache,以減少不必要的重複查找
private int ipBegin;
private int ipEnd;
@SuppressWarnings("resource")
public IPSeekerUtil(File file) throws Exception {
buffer = new RandomAccessFile(file, "r").getChannel().map(
FileChannel.MapMode.READ_ONLY, 0, file.length());
if (buffer.order().toString().equals(ByteOrder.BIG_ENDIAN.toString())) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
ipBegin = readInt(0);
ipEnd = readInt(4);
if (ipBegin == -1 || ipEnd == -1) {
throw new IOException("IP地址信息文件格式有錯誤,IP顯示功能將無法使用");
}
log.debug("使用IP地址庫:" + file.getAbsolutePath());
}
/**
* 給定一個ip 得到一個 ip地址信息
*
* @param ip
* @return
*/
public String getAddress(String ip) {
return getCountry(ip) + " " + getArea(ip);
}
/**
* 根據IP得到國家名
*
* @param ip
* IP的字符串形式
* @return 國家名字符串
*/
public String getCountry(String ip) {
IPLocation cache = getIpLocation(ip);
return cache.getCountry();
}
/**
* 根據IP得到地區名
*
* @param ip
* IP的字符串形式
* @return 地區名字符串
*/
public String getArea(String ip) {
IPLocation cache = getIpLocation(ip);
return cache.getArea();
}
/**
* 獲得一個IP地址信息
*
* @param ip
* @return
*/
public IPLocation getIpLocation(String ip) {
IPLocation ipLocation = null;
try {
if (cache.get(ip) != null) {
return cache.get(ip);
}
ipLocation = getIPLocation(getIpByteArrayFromString(ip));
if (ipLocation != null) {
cache.put(ip, ipLocation);
}
} catch (Exception e) {
log.error(e);
}
if (ipLocation == null) {
ipLocation = new IPLocation();
ipLocation.setCountry("未知國家");
ipLocation.setArea("未知地區");
}
return ipLocation;
}
/**
* 給定一個地點的不完全名字,得到一系列包含s子串的IP範圍記錄
*
* @param s
* 地點子串
* @return 包含IPEntry類型的List
*/
public List<IPEntry> getIPEntries(String s) {
List<IPEntry> ret = new ArrayList<IPEntry>();
byte[] b4 = new byte[4];
int endOffset = ipEnd + 4;
for (int offset = ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
// 讀取結束IP偏移
int temp = readInt3(offset);
// 如果temp不等於-1,讀取IP的地點信息
if (temp != -1) {
IPLocation loc = getIPLocation(temp);
// 判斷是否這個地點裏麪包含了s子串,如果包含了,添加這個記錄到List中,如果沒有,繼續
if (loc.country.indexOf(s) != -1 || loc.area.indexOf(s) != -1) {
IPEntry entry = new IPEntry();
entry.country = loc.country;
entry.area = loc.area;
// 得到起始IP
readIP(offset - 4, b4);
entry.beginIp = getIpStringFromBytes(b4);
// 得到結束IP
readIP(temp, b4);
entry.endIp = getIpStringFromBytes(b4);
// 添加該記錄
ret.add(entry);
}
}
}
return ret;
}
/**
* 根據ip搜索ip信息文件,得到IPLocation結構,所搜索的ip參數從類成員ip中得到
*
* @param ip
* 要查詢的IP
* @return IPLocation結構
*/
private IPLocation getIPLocation(byte[] ip) {
IPLocation info = null;
int offset = locateIP(ip);
if (offset != -1) {
info = getIPLocation(offset);
}
return info;
}
// -----------------以下爲內部方法
/**
* 讀取4個字節
*
* @param offset
* @return
*/
private int readInt(int offset) {
buffer.position(offset);
return buffer.getInt();
}
private int readInt3(int offset) {
buffer.position(offset);
return buffer.getInt() & 0x00FFFFFF;
}
/**
* 從內存映射文件的offset位置得到一個0結尾字符串
*
* @param offset
* @return
*/
private String readString(int offset) {
try {
byte[] buf = new byte[100];
buffer.position(offset);
int i;
for (i = 0, buf[i] = buffer.get(); buf[i] != 0; buf[++i] = buffer
.get()) {
}
if (i != 0) {
return getString(buf, 0, i, "GBK");
}
} catch (IllegalArgumentException e) {
log.error(e);
}
return "";
}
/**
* 從offset位置讀取四個字節的ip地址放入ip數組中,讀取後的ip爲big-endian格式,但是
* 文件中是little-endian形式,將會進行轉換
*
* @param offset
* @param ip
*/
private void readIP(int offset, byte[] ip) {
buffer.position(offset);
buffer.get(ip);
byte temp = ip[0];
ip[0] = ip[3];
ip[3] = temp;
temp = ip[1];
ip[1] = ip[2];
ip[2] = temp;
}
/**
* 把類成員ip和beginIp比較,注意這個beginIp是big-endian的
*
* @param ip
* 要查詢的IP
* @param beginIp
* 和被查詢IP相比較的IP
* @return 相等返回0,ip大於beginIp則返回1,小於返回-1。
*/
private int compareIP(byte[] ip, byte[] beginIp) {
for (int i = 0; i < 4; i++) {
int r = compareByte(ip[i], beginIp[i]);
if (r != 0) {
return r;
}
}
return 0;
}
/**
* 把兩個byte當作無符號數進行比較
*
* @param b1
* @param b2
* @return 若b1大於b2則返回1,相等返回0,小於返回-1
*/
private int compareByte(byte b1, byte b2) {
if ((b1 & 0xFF) > (b2 & 0xFF)) // 比較是否大於
{
return 1;
} else if ((b1 ^ b2) == 0)// 判斷是否相等
{
return 0;
} else {
return -1;
}
}
/**
* 這個方法將根據ip的內容,定位到包含這個ip國家地區的記錄處,返回一個絕對偏移 方法使用二分法查找。
*
* @param ip
* 要查詢的IP
* @return 如果找到了,返回結束IP的偏移,如果沒有找到,返回-1
*/
private int locateIP(byte[] ip) {
int m = 0;
int r;
byte[] b4 = new byte[4];
// 比較第一個ip項
readIP(ipBegin, b4);
r = compareIP(ip, b4);
if (r == 0) {
return ipBegin;
} else if (r < 0) {
return -1;
}
// 開始二分搜索
for (int i = ipBegin, j = ipEnd; i < j;) {
m = getMiddleOffset(i, j);
readIP(m, b4);
r = compareIP(ip, b4);
// log.debug(Utils.getIpStringFromBytes(b));
if (r > 0) {
i = m;
} else if (r < 0) {
if (m == j) {
j -= IP_RECORD_LENGTH;
m = j;
} else {
j = m;
}
} else {
return readInt3(m + 4);
}
}
// 如果循環結束了,那麼i和j必定是相等的,這個記錄爲最可能的記錄,但是並非
// 肯定就是,還要檢查一下,如果是,就返回結束地址區的絕對偏移
m = readInt3(m + 4);
readIP(m, b4);
r = compareIP(ip, b4);
if (r <= 0) {
return m;
} else {
return -1;
}
}
/**
* 得到begin偏移和end偏移中間位置記錄的偏移
*
* @param begin
* @param end
* @return
*/
private int getMiddleOffset(int begin, int end) {
int records = (end - begin) / IP_RECORD_LENGTH;
records >>= 1;
if (records == 0) {
records = 1;
}
return begin + records * IP_RECORD_LENGTH;
}
/**
* @param offset
* @return
*/
private IPLocation getIPLocation(int offset) {
IPLocation loc = new IPLocation();
// 跳過4字節ip
buffer.position(offset + 4);
// 讀取第一個字節判斷是否標誌字節
byte b = buffer.get();
if (b == AREA_FOLLOWED) {
// 讀取國家偏移
int countryOffset = readInt3();
// 跳轉至偏移處
buffer.position(countryOffset);
// 再檢查一次標誌字節,因爲這個時候這個地方仍然可能是個重定向
b = buffer.get();
if (b == NO_AREA) {
loc.country = readString(readInt3());
buffer.position(countryOffset + 4);
} else {
loc.country = readString(countryOffset);
}
// 讀取地區標誌
loc.area = readArea(buffer.position());
} else if (b == NO_AREA) {
loc.country = readString(readInt3());
loc.area = readArea(offset + 8);
} else {
loc.country = readString(buffer.position() - 1);
loc.area = readArea(buffer.position());
}
return loc;
}
/**
* @param offset
* @return
*/
private String readArea(int offset) {
buffer.position(offset);
byte b = buffer.get();
if (b == 0x01 || b == 0x02) {
int areaOffset = readInt3();
if (areaOffset == 0) {
return "未知地區";
} else {
return readString(areaOffset);
}
} else {
return readString(offset);
}
}
/**
* 從內存映射文件的當前位置開始的3個字節讀取一個int
*
* @return
*/
private int readInt3() {
return buffer.getInt() & 0x00FFFFFF;
}
/**
* 從ip的字符串形式得到字節數組形式
*
* @param ip
* 字符串形式的ip
* @return 字節數組形式的ip
*/
private static byte[] getIpByteArrayFromString(String ip) throws Exception {
byte[] ret = new byte[4];
java.util.StringTokenizer st = new java.util.StringTokenizer(ip, ".");
try {
ret[0] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
ret[1] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
ret[2] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
ret[3] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
} catch (Exception e) {
throw e;
}
return ret;
}
/**
* 根據某種編碼方式將字節數組轉換成字符串
*
* @param b
* 字節數組
* @param offset
* 要轉換的起始位置
* @param len
* 要轉換的長度
* @param encoding
* 編碼方式
* @return 如果encoding不支持,返回一個缺省編碼的字符串
*/
private static String getString(byte[] b, int offset, int len,
String encoding) {
try {
return new String(b, offset, len, encoding);
} catch (UnsupportedEncodingException e) {
return new String(b, offset, len);
}
}
/**
* @param ip
* ip的字節數組形式
* @return 字符串形式的ip
*/
private static String getIpStringFromBytes(byte[] ip) {
StringBuffer sb = new StringBuffer();
sb.append(ip[0] & 0xFF);
sb.append('.');
sb.append(ip[1] & 0xFF);
sb.append('.');
sb.append(ip[2] & 0xFF);
sb.append('.');
sb.append(ip[3] & 0xFF);
return sb.toString();
}
public class IPLocation {
private String country;// 所在國家
private String area;// 所在地區
public IPLocation() {
}
public IPLocation(String country, String area) {
this.country = country;
this.area = area;
}
public IPLocation getCopy() {
return new IPLocation(country, area);
}
public String getArea() {
return " CZ88.NET".equals(area) ? "" : area;
}
public void setArea(String area) {
this.area = area;
}
public String getCountry() {
return " CZ88.NET".equals(country) ? "" : country;
}
public void setCountry(String country) {
this.country = country;
}
}
/**
* * 一條IP範圍記錄,不僅包括國家和區域,也包括起始IP和結束IP *
*
*/
public class IPEntry {
public String beginIp;
public String endIp;
public String country;
public String area;
/**
* 構造函數
*/
public IPEntry() {
}
@Override
public String toString() {
return new StringBuilder(this.area).append(";")
.append(this.country).append(";").append("IP範圍:")
.append(beginIp).append("-").append(endIp).toString();
}
}
}
調用
由於讀取本地文件地址庫,所以採用單例模式調用
public class IpServiceImpl implements IIpService {
private static Logger log = Logger.getLogger(IpServiceImpl.class);
private static IPSeekerUtil ipSeeker;
@Override
public String getIpArea(String ip) {
if(ipSeeker == null){
String file = (IPSeekerUtil.class.getResource("/").toString() + "QQWry.dat")
.substring(6);
try {
ipSeeker = new IPSeekerUtil(new File(file));
} catch (Exception e) {
log.error("IP地址庫實例化出錯", e);
}
}
return ipSeeker.getAddress(ip);
}
}