JAVA 분석 순수 IP 주소 라 이브 러 리
해석 의 주 클래스
package cmz.ip;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
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 java.util.Map;
import org.apache.log4j.Level;
public class IPSeeker {
// IP
private String IP_FILE="QQWry.Dat";
//
private String INSTALL_DIR="f:/qqwry";
// ,
private static final int IP_RECORD_LENGTH = 7;
private static final byte REDIRECT_MODE_1 = 0x01;
private static final byte REDIRECT_MODE_2 = 0x02;
// cache, ip cache,
private Map<String, IPLocation> ipCache;
//
private RandomAccessFile ipFile;
//
private MappedByteBuffer mbb;
//
private long ipBegin, ipEnd;
//
private IPLocation loc;
private byte[] buf;
private byte[] b4;
private byte[] b3;
public IPSeeker(String fileName,String dir) {
this.INSTALL_DIR=dir;
this.IP_FILE=fileName;
ipCache = new HashMap<String, IPLocation>();
loc = new IPLocation();
buf = new byte[100];
b4 = new byte[4];
b3 = new byte[3];
try {
ipFile = new RandomAccessFile(IP_FILE, "r");
} catch (FileNotFoundException e) {
// , ,
// ip
String filename = new File(IP_FILE).getName().toLowerCase();
File[] files = new File(INSTALL_DIR).listFiles();
for(int i = 0; i < files.length; i++) {
if(files[i].isFile()) {
if(files[i].getName().toLowerCase().equals(filename)) {
try {
ipFile = new RandomAccessFile(files[i], "r");
} catch (FileNotFoundException e1) {
LogFactory.log("IP ,IP ",Level.ERROR,e1);
ipFile = null;
}
break;
}
}
}
}
// ,
if(ipFile != null) {
try {
ipBegin = readLong4(0);
ipEnd = readLong4(4);
if(ipBegin == -1 || ipEnd == -1) {
ipFile.close();
ipFile = null;
}
} catch (IOException e) {
LogFactory.log("IP ,IP ",Level.ERROR,e);
ipFile = null;
}
}
}
/**
* , s IP
* @param s
* @return IPEntry List
*/
public List getIPEntriesDebug(String s) {
List<IPEntry> ret = new ArrayList<IPEntry>();
long endOffset = ipEnd + 4;
for(long offset = ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
// IP
long temp = readLong3(offset);
// temp -1, IP
if(temp != -1) {
IPLocation ipLoc = getIPLocation(temp);
// s , , List , ,
if(ipLoc.getCountry().indexOf(s) != -1 || ipLoc.getArea().indexOf(s) != -1) {
IPEntry entry = new IPEntry();
entry.country = ipLoc.getCountry();
entry.area = ipLoc.getArea();
// IP
readIP(offset - 4, b4);
entry.beginIp = Util.getIpStringFromBytes(b4);
// IP
readIP(temp, b4);
entry.endIp = Util.getIpStringFromBytes(b4);
//
ret.add(entry);
}
}
}
return ret;
}
public IPLocation getIPLocation(String ip){
IPLocation location=new IPLocation();
location.setArea(this.getArea(ip));
location.setCountry(this.getCountry(ip));
return location;
}
/**
* , s IP
* @param s
* @return IPEntry List
*/
public List<IPEntry> getIPEntries(String s) {
List<IPEntry> ret = new ArrayList<IPEntry>();
try {
// IP
if(mbb == null) {
FileChannel fc = ipFile.getChannel();
mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
mbb.order(ByteOrder.LITTLE_ENDIAN);
}
int endOffset = (int)ipEnd;
for(int offset = (int)ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
int temp = readInt3(offset);
if(temp != -1) {
IPLocation ipLoc = getIPLocation(temp);
// s , , List , ,
if(ipLoc.getCountry().indexOf(s) != -1 || ipLoc.getArea().indexOf(s) != -1) {
IPEntry entry = new IPEntry();
entry.country = ipLoc.getCountry();
entry.area = ipLoc.getArea();
// IP
readIP(offset - 4, b4);
entry.beginIp = Util.getIpStringFromBytes(b4);
// IP
readIP(temp, b4);
entry.endIp = Util.getIpStringFromBytes(b4);
//
ret.add(entry);
}
}
}
} catch (IOException e) {
LogFactory.log("",Level.ERROR,e);
}
return ret;
}
/**
* offset 3 int
* @param offset
* @return
*/
private int readInt3(int offset) {
mbb.position(offset);
return mbb.getInt() & 0x00FFFFFF;
}
/**
* 3 int
* @return
*/
private int readInt3() {
return mbb.getInt() & 0x00FFFFFF;
}
/**
* IP
* @param ip ip
* @return
*/
public String getCountry(byte[] ip) {
// ip
if(ipFile == null)
return Message.bad_ip_file;
// ip, ip
String ipStr = Util.getIpStringFromBytes(ip);
// cache ip ,
if(ipCache.containsKey(ipStr)) {
IPLocation ipLoc = ipCache.get(ipStr);
return ipLoc.getCountry();
} else {
IPLocation ipLoc = getIPLocation(ip);
ipCache.put(ipStr, ipLoc.getCopy());
return ipLoc.getCountry();
}
}
/**
* IP
* @param ip IP
* @return
*/
public String getCountry(String ip) {
return getCountry(Util.getIpByteArrayFromString(ip));
}
/**
* IP
* @param ip ip
* @return
*/
public String getArea(byte[] ip) {
// ip
if(ipFile == null)
return Message.bad_ip_file;
// ip, ip
String ipStr = Util.getIpStringFromBytes(ip);
// cache ip ,
if(ipCache.containsKey(ipStr)) {
IPLocation ipLoc = ipCache.get(ipStr);
return ipLoc.getArea();
} else {
IPLocation ipLoc = getIPLocation(ip);
ipCache.put(ipStr, ipLoc.getCopy());
return ipLoc.getArea();
}
}
/**
* IP
* @param ip IP
* @return
*/
public String getArea(String ip) {
return getArea(Util.getIpByteArrayFromString(ip));
}
/**
* ip ip , IPLocation , ip ip
* @param ip IP
* @return IPLocation
*/
private IPLocation getIPLocation(byte[] ip) {
IPLocation info = null;
long offset = locateIP(ip);
if(offset != -1)
info = getIPLocation(offset);
if(info == null) {
info = new IPLocation();
info.setCountry ( Message.unknown_country);
info.setArea(Message.unknown_area);
}
return info;
}
/**
* offset 4 long, java big-endian ,
*
* @param offset
* @return long , -1
*/
private long readLong4(long offset) {
long ret = 0;
try {
ipFile.seek(offset);
ret |= (ipFile.readByte() & 0xFF);
ret |= ((ipFile.readByte() << 8) & 0xFF00);
ret |= ((ipFile.readByte() << 16) & 0xFF0000);
ret |= ((ipFile.readByte() << 24) & 0xFF000000);
return ret;
} catch (IOException e) {
return -1;
}
}
/**
* offset 3 long, java big-endian ,
*
* @param offset
* @return long , -1
*/
private long readLong3(long offset) {
long ret = 0;
try {
ipFile.seek(offset);
ipFile.readFully(b3);
ret |= (b3[0] & 0xFF);
ret |= ((b3[1] << 8) & 0xFF00);
ret |= ((b3[2] << 16) & 0xFF0000);
return ret;
} catch (IOException e) {
return -1;
}
}
/**
* 3 long
* @return long , -1
*/
private long readLong3() {
long ret = 0;
try {
ipFile.readFully(b3);
ret |= (b3[0] & 0xFF);
ret |= ((b3[1] << 8) & 0xFF00);
ret |= ((b3[2] << 16) & 0xFF0000);
return ret;
} catch (IOException e) {
return -1;
}
}
/**
* offset ip ip , ip big-endian ,
* little-endian ,
* @param offset
* @param ip
*/
private void readIP(long offset, byte[] ip) {
try {
ipFile.seek(offset);
ipFile.readFully(ip);
byte temp = ip[0];
ip[0] = ip[3];
ip[3] = temp;
temp = ip[1];
ip[1] = ip[2];
ip[2] = temp;
} catch (IOException e) {
LogFactory.log("",Level.ERROR,e);
}
}
/**
* offset ip ip , ip big-endian ,
* little-endian ,
* @param offset
* @param ip
*/
private void readIP(int offset, byte[] ip) {
mbb.position(offset);
mbb.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 long locateIP(byte[] ip) {
long m = 0;
int r;
// ip
readIP(ipBegin, b4);
r = compareIP(ip, b4);
if(r == 0) return ipBegin;
else if(r < 0) return -1;
//
for(long 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 readLong3(m + 4);
}
// , i j , ,
// , , ,
m = readLong3(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 long getMiddleOffset(long begin, long end) {
long records = (end - begin) / IP_RECORD_LENGTH;
records >>= 1;
if(records == 0) records = 1;
return begin + records * IP_RECORD_LENGTH;
}
/**
* ip , IPLocation
* @param offset
* @return IPLocation
*/
private IPLocation getIPLocation(long offset) {
try {
// 4 ip
ipFile.seek(offset + 4);
//
byte b = ipFile.readByte();
if(b == REDIRECT_MODE_1) {
//
long countryOffset = readLong3();
//
ipFile.seek(countryOffset);
// ,
b = ipFile.readByte();
if(b == REDIRECT_MODE_2) {
loc.setCountry ( readString(readLong3()));
ipFile.seek(countryOffset + 4);
} else
loc.setCountry ( readString(countryOffset));
//
loc.setArea( readArea(ipFile.getFilePointer()));
} else if(b == REDIRECT_MODE_2) {
loc.setCountry ( readString(readLong3()));
loc.setArea( readArea(offset + 8));
} else {
loc.setCountry ( readString(ipFile.getFilePointer() - 1));
loc.setArea( readArea(ipFile.getFilePointer()));
}
return loc;
} catch (IOException e) {
return null;
}
}
/**
* ip , IPLocation ,
* @param offset
* @return IPLocation
*/
private IPLocation getIPLocation(int offset) {
// 4 ip
mbb.position(offset + 4);
//
byte b = mbb.get();
if(b == REDIRECT_MODE_1) {
//
int countryOffset = readInt3();
//
mbb.position(countryOffset);
// ,
b = mbb.get();
if(b == REDIRECT_MODE_2) {
loc.setCountry ( readString(readInt3()));
mbb.position(countryOffset + 4);
} else
loc.setCountry ( readString(countryOffset));
//
loc.setArea(readArea(mbb.position()));
} else if(b == REDIRECT_MODE_2) {
loc.setCountry ( readString(readInt3()));
loc.setArea(readArea(offset + 8));
} else {
loc.setCountry ( readString(mbb.position() - 1));
loc.setArea(readArea(mbb.position()));
}
return loc;
}
/**
* offset ,
* @param offset
* @return
* @throws IOException
*/
private String readArea(long offset) throws IOException {
ipFile.seek(offset);
byte b = ipFile.readByte();
if(b == REDIRECT_MODE_1 || b == REDIRECT_MODE_2) {
long areaOffset = readLong3(offset + 1);
if(areaOffset == 0)
return Message.unknown_area;
else
return readString(areaOffset);
} else
return readString(offset);
}
/**
* @param offset
* @return
*/
private String readArea(int offset) {
mbb.position(offset);
byte b = mbb.get();
if(b == REDIRECT_MODE_1 || b == REDIRECT_MODE_2) {
int areaOffset = readInt3();
if(areaOffset == 0)
return Message.unknown_area;
else
return readString(areaOffset);
} else
return readString(offset);
}
/**
* offset 0
* @param offset
* @return ,
*/
private String readString(long offset) {
try {
ipFile.seek(offset);
int i;
for(i = 0, buf[i] = ipFile.readByte(); buf[i] != 0; buf[++i] = ipFile.readByte());
if(i != 0)
return Util.getString(buf, 0, i, "GBK");
} catch (IOException e) {
LogFactory.log("",Level.ERROR,e);
}
return "";
}
/**
* offset 0
* @param offset
* @return ,
*/
private String readString(int offset) {
try {
mbb.position(offset);
int i;
for(i = 0, buf[i] = mbb.get(); buf[i] != 0; buf[++i] = mbb.get());
if(i != 0)
return Util.getString(buf, 0, i, "GBK");
} catch (IllegalArgumentException e) {
LogFactory.log("",Level.ERROR,e);
}
return "";
}
}
실제 항목 에 서 는 spring 을 사용 하여 IP 주소 라 이브 러 리 파일 의 이름과 소재 디 렉 터 리 를 주입 하고 IPSeeker 의 단일 인 스 턴 스 를 확보 할 수 있 습 니 다.다음은 도구 클래스 입 니 다. string 과 btye 배열 을 서로 바 꾸 는 클래스 입 니 다.
package cmz.ip;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import org.apache.log4j.Level;
/**
* ,
*/
public class Util {
private static StringBuilder sb = new StringBuilder();
/**
* ip
* @param ip ip
* @return ip
*/
public static byte[] getIpByteArrayFromString(String ip) {
byte[] ret = new byte[4];
StringTokenizer st = new 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) {
LogFactory.log(" ip ", Level.ERROR, e);
}
return ret;
}
/**
* @param ip ip
* @return ip
*/
public static String getIpStringFromBytes(byte[] ip) {
sb.delete(0, sb.length());
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();
}
/**
*
* @param b
* @param offset
* @param len
* @param encoding
* @return encoding ,
*/
public 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);
}
}
}
다음은 상수 치 의 종류 로 인터페이스 형식 으로 정의 하 는 것 이 적지 않다.
package cmz.ip;
public interface Message {
String bad_ip_file="IP ";
String unknown_country=" ";
String unknown_area=" ";
}
국가 와 지역 을 봉인 하 는 실체 류
package cmz.ip;
/**
*
* @category ip , ,ip
*/
public class IPLocation {
private String country;
private String area;
public IPLocation() {
country = area = "";
}
public IPLocation getCopy() {
IPLocation ret = new IPLocation();
ret.country = country;
ret.area = area;
return ret;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getArea() {
return area;
}
public void setArea(String area) {
// , IP CZ88.NET,
if(area.trim().equals("CZ88.NET")){
this.area=" ";
}else{
this.area = area;
}
}
}
한 번 은 범위 기록 류 입 니 다.
package cmz.ip;
/**
* <pre>
* IP , , IP IP
* </pre>
*/
public class IPEntry {
public String beginIp;
public String endIp;
public String country;
public String area;
/**
*
*/
public IPEntry() {
beginIp = endIp = country = area = "";
}
}
로그 기록 클래스
package cmz.ip;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
*
*
*
*/
public class LogFactory {
private static final Logger logger;
static {
logger = Logger.getLogger("stdout");
logger.setLevel(Level.DEBUG);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
public static Level getLogLevel(){
return logger.getLevel();
}
}
다음은 테스트 클래스 입 니 다.
package cmz.ip;
public class IPConvert {
/**
* ip .
*
* @param ip
* @return
*/
public static long ip2long(String ip) {
String[] ips = ip.split("[.]");
long num = 16777216L * Long.parseLong(ips[0]) + 65536L
* Long.parseLong(ips[1]) + 256 * Long.parseLong(ips[2])
+ Long.parseLong(ips[3]);
return num;
}
/**
* ip .
*
* @param ipLong
* @return
*/
public static String long2ip(long ipLong) {
// long ipLong = 1037591503;
long mask[] = { 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 };
long num = 0;
StringBuffer ipInfo = new StringBuffer();
for (int i = 0; i < 4; i++) {
num = (ipLong & mask[i]) >> (i * 8);
if (i > 0)
ipInfo.insert(0, ".");
ipInfo.insert(0, Long.toString(num, 10));
}
return ipInfo.toString();
}
public static void main(String[] args) {
// System.out.println(ip2long("58.20.43.13"));
// System.out.println(long2ip(3395968127l));
// ,
IPSeeker ip = new IPSeeker("QQWry.Dat", "D:/qqwry");
// IP 58.20.43.13
System.out.println(ip.getIPLocation("114.80.89.15").getCountry() + ":" + ip.getIPLocation("114.80.89.15").getArea());
}
}
당 수출: 호남성 장사 시: 왕 통
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.