com.topsem.common.net.IPSeeker.java Source code

Java tutorial

Introduction

Here is the source code for com.topsem.common.net.IPSeeker.java

Source

package com.topsem.common.net;
/*
 * LumaQQ - Java QQ Client
 *
 * Copyright (C) 2004 luma < stubma@163.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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;

/**
 *  * ??QQwry.dat?ip??QQwry.dat?
 * . 8
 *        1. IP??? 4
 *     2. ?IP??? 4
 * . "??//"
 *     ip?????
 *     1. 
 *     2. 
 *     ???
 *     1. 0?
 *     2. 4?0x10x2
 *           a. 0x1????????????
 *        b. 0x2????
 *        ?0x10x2??????
 *           0x10x2???3???
 *        0
 * . "?/????"
 *     1. ??7??
 *        a. IP?4
 *        b. ?ip????3
 *
 * ?ip?????little-endian?java
 * big-endian????
 *
 *
 * @author 
 *
 * IP?
 * 
 */
public class IPSeeker {

    private Log log = LogFactory.getLog(IPSeeker.class);

    /**
     * ??ip???ip
     * @author 
     */
    public class IPLocation {

        private String country;
        private String area;

        public String getArea() {
            if (" CZ88.NET".equals(area)) {
                area = "";
            }
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }

        public String getCountry() {
            if (" CZ88.NET".equals(country)) {
                country = "";
            }
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public IPLocation() {
            area = "";
            country = "";
        }

        public IPLocation getCopy() {
            IPLocation ret = new IPLocation();
            ret.country = country;
            ret.area = area;
            return ret;
        }
    }

    /** *
     * ?IP?IP?IP *
     * @author 
     */
    public class IPEntry {

        public String beginIp;
        public String endIp;
        public String country;
        public String area;

        /**
         * 
         */
        public IPEntry() {
            beginIp = endIp = country = area = "";
        }

        @Override
        public String toString() {
            return this.area + "  " + this.country + "IP:" + this.beginIp + "-" + this.endIp;
        }
    }

    // ?
    private static final int IP_RECORD_LENGTH = 7;
    private static final byte AREA_FOLLOWED = 0x01;
    private static final byte NO_AREA = 0x2;
    // ,??IO ?
    private MappedByteBuffer mbb;
    // ?
    private RandomAccessFile ipFile;
    // ??cacheipcache?????
    private HashMap<String, IPLocation> ipCache;
    // ????
    private int ipBegin, ipEnd;

    public IPSeeker(File ipFile) throws Exception {
        this.ipFile = new RandomAccessFile(ipFile, "r");
        ipCache = new HashMap<String, IPLocation>();
        FileChannel fc = this.ipFile.getChannel();
        mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
        mbb.order(ByteOrder.LITTLE_ENDIAN);
        ipBegin = readInt(0);
        ipEnd = readInt(4);
        if (ipBegin == -1 || ipEnd == -1) {
            throw new IOException("IP???IP");
        }
        log.debug("IP?:" + ipFile.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 (ipCache.get(ip) != null) {
                return ipCache.get(ip);
            }
            ipLocation = getIPLocation(getIpByteArrayFromString(ip));
            if (ipLocation != null) {
                ipCache.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 ?IPEntryList
     */
    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) {
        mbb.position(offset);
        return mbb.getInt();
    }

    private int readInt3(int offset) {
        mbb.position(offset);
        return mbb.getInt() & 0x00FFFFFF;
    }

    /**
     * offset?0
     * @param offset
     * @return
     */
    private String readString(int offset) {
        try {
            byte[] buf = new byte[100];
            mbb.position(offset);
            int i;
            for (i = 0, buf[i] = mbb.get(); buf[i] != 0; buf[++i] = mbb.get()) {
            }
            if (i != 0) {
                return getString(buf, 0, i, "GBK");
            }
        } catch (IllegalArgumentException e) {
            log.error(e);
        }
        return "";
    }

    /**
     * offset??ip?ip??ipbig-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;
    }

    /**
     * ?ipbeginIp?beginIpbig-endian
     * @param ip ?IP
     * @param beginIp IPIP
     * @return 0ipbeginIp1?-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 b1b210?-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);
            }
        }
        // ?ij??
        //     ??????
        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();
        // 4ip
        mbb.position(offset + 4);
        // ??
        byte b = mbb.get();
        if (b == AREA_FOLLOWED) {
            // ???
            int countryOffset = readInt3();
            // ??
            mbb.position(countryOffset);
            // ?????
            b = mbb.get();
            if (b == NO_AREA) {
                loc.country = readString(readInt3());
                mbb.position(countryOffset + 4);
            } else {
                loc.country = readString(countryOffset);
            }
            // ?
            loc.area = readArea(mbb.position());
        } else if (b == NO_AREA) {
            loc.country = readString(readInt3());
            loc.area = readArea(offset + 8);
        } else {
            loc.country = readString(mbb.position() - 1);
            loc.area = readArea(mbb.position());
        }
        return loc;
    }

    /**
     * @param offset
     * @return
     */
    private String readArea(int offset) {
        mbb.position(offset);
        byte b = mbb.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 mbb.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 static void main(String[] args) {
    //        try {
    //            String rootPath = IPSeeker.class.getResource("/").getPath();
    //            IPSeeker ipSeeker = new IPSeeker(new File(rootPath + "QQWry.dat"));
    //            IPLocation ipLocation = ipSeeker.getIpLocation("121.8.243.50");
    //            System.out.println(ipSeeker.getAddress("121.8.243.50"));
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //    }
}