资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

强大的IP地址定位库--ip2region的初步使用

2019年05月05日 开源的IP 地址定位库 ip2region 1.9.0 发布了,功能还是很不错的,下面我就应用下ip2region,来解析ip的地址

成都创新互联是一家专业提供吉安企业网站建设,专注与网站设计、网站建设、H5高端网站建设、小程序制作等业务。10年已为吉安众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

一、下载ip库并解压
地址为:https://github.com/lionsoul2014/ip2region/archive/v1.9.0-release.tar.gz
解压
强大的IP地址定位库--ip2region 的初步使用

把ip2region.db粘贴到我们maven工程的resources下
强大的IP地址定位库--ip2region 的初步使用

二、添加ip2region依赖


            org.lionsoul
            ip2region
            1.7.2

三、实现IPUtil工具类

import java.io.File;
import java.lang.reflect.Method;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

public class IPUtil {
    public static String getCityInfo(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);

        return dataBlock.getRegion();

    } catch (Exception e) {
        e.printStackTrace();
    }

        return null;
}

}

四、测试
这里我是用的Junit进行单元测试,你也可以自己写个main方法测试即可
添加junit依赖


            junit
            junit
            4.12

编写测试类

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class IPUtilTest {
    private IPUtil ipUtil;

    @Before
    public void setUp(){
        ipUtil=new IPUtil();
    }
    @After
    public void tearDown(){
        ipUtil=null;
    }
    @Test
    public void getCityInfo(){
        String ip = "220.248.12.158";
        System.out.println(ipUtil.getCityInfo(ip));
    }
}

强大的IP地址定位库--ip2region 的初步使用
总结:很方便,其实我觉得比纯真的要好多了~


分享标题:强大的IP地址定位库--ip2region的初步使用
本文路径:http://cdkjz.cn/article/gggjid.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220