Python如何通过ip2region解析IP获得地域信息

 更新时间:2022年11月30日 10:57:47   作者:亿万行代码的梦  
这篇文章主要介绍了Python如何通过ip2region解析IP获得地域信息,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

通过ip2region解析IP获得地域信息

目标,从给的读取给的ip地址文件解析出ip地域名并输出CSV文件,我选用的是开源ip2region。ip2region地址

下载好后直接用pycharm打开,因为我用的是python所以其他语言我就忽略了。

这里我对代码进行了编辑从而实现自己的目的。


主要对benchmark.py进行了修改。

代码如下:

import threading
import time, sys

from ip2Region import Ip2Region

class BenchmarkThread(threading.Thread):
    __searcher = None
    __lock = None

    def __init__(self, searcher, lock):
        self.__searcher = searcher
        self.__lock = lock
        threading.Thread.__init__(self)

    def run(self):
    	#输入路径,每行为一个IP地址
        for IP in open("D:\****\****.txt"):
            self.__lock.acquire()
            try:
                data = self.__searcher.memorySearch(IP)
                region=str(data["region"].decode('utf-8'))
                #print(region.split("|"))
                city=""
                province=""
                regions=region.split("|")
                if(regions[3]=="0"):
                    city=""
                else:
                    city=regions[3]

                if (regions[2] == "0"):
                    province = ""
                else:
                    province = regions[2]
print(IP.strip()+","+regions[0]+province+city+regions[4])
                result=IP.strip()+","+regions[0]+province+city+" "+regions[4]
                with open('*****.csv', 'a') as f:  # 设置文件对象
                    f.write(result+"\n")

            finally:
                self.__lock.release()

if __name__ == "__main__":
    dbFile = "D:\pythonProject\hx_hdfs_local\ip2region-master\data\ip2region.db"
    if ( len(sys.argv) > 2 ):
        dbFile = sys.argv[1];

    threads = []
    searcher = Ip2Region(dbFile)
    lock = threading.Lock()

    for i in range(1):
        t = BenchmarkThread(searcher, lock)
        threads.append(t)

    sTime = time.time() * 1
    for t in threads:
        t.start()

    for t in threads:
        t.join()
    eTime = time.time() * 1

    #print("Benchmark done: %5f" % (eTime - sTime))

结果对比:


原始数据


结果数据

ip2region的使用总结

ip2region 简介

根据它获取一个具体ip的信息,通过IP解析出国家、具体地址、网络服务商等相关信息。

ip2region 实际应用

在开发中,我们需要记录登陆的日志信息,关于登陆者的ip和位置信息,可以通过ip2region来实现。

Spring Boot集成ip2region

第一步:pom.xml引入

    <properties>
        <ip2region.version>1.7.2</ip2region.version>
    </properties>
 
   <dependency>
        <groupId>org.lionsoul</groupId>
        <artifactId>ip2region</artifactId>
        <version>${ip2region.version}</version>
    </dependency>

第二步:下载ip2region.db

$ git clone https://gitee.com/lionsoul/ip2region.git

下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下

下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下

第三步:ip2region 工具类

功能:主要基于IP获取当前位置信息。

import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
 
/**
 * @author zhouzhiwengang
 */
public class AddressUtil {
 
    private static Logger log = LoggerFactory.getLogger(AddressUtil.class);
 
    @SuppressWarnings("all")
    public static String getCityInfo(String ip) {
        //db
        String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
        File file = new File(dbPath);
 
        if (!file.exists()) {
            log.info("地址库文件不存在,进行其他处理");
            String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
            dbPath = tmpDir + File.separator + "ip2region.db";
            log.info("临时文件路径:{}", dbPath);
            file = new File(dbPath);
            if (!file.exists() || (System.currentTimeMillis() - file.lastModified() > 86400000L)) {
                log.info("文件不存在或者文件存在时间超过1天进入...");
                try {
                    InputStream inputStream = new ClassPathResource("ip2region/ip2region.db").getInputStream();
                    IOUtils.copy(inputStream, new FileOutputStream(file));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
 
        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        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) {
                log.error("Error: Invalid ip address");
            }
            dataBlock = (DataBlock) method.invoke(searcher, ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

知识拓展

遇到的问题:由于AddressUtil.java 工具类是处于项目common(基础通用模块),但部署到tomcat 容器中,提示无法加载ip2region.db 数据库资源文件。

产生上述问题的原因是:项目common(基础通用模块)没有把resources 资源文件夹下的相关资源打包,仅需要将ip2region.db 打包之项目common(基础通用模块).jar 中即可。

解决办法:改造项目common(基础通用模块)的pom.xml 文件,添加如下代码片段:

<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**.*</include>
					<include>**/*.*</include><!-- i18n能读取到 -->
					<include>**/*/*.*</include>
				</includes>
			</resource>
		</resources>
	</build>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python使用openpyxl库读取Excel文件数据

    python使用openpyxl库读取Excel文件数据

    openpyxl是一个功能强大的库,可以轻松地实现Excel文件的读写操作,本文将介绍如何使用openpyxl库读取Excel文件中的数据,感兴趣的小伙伴可以了解下
    2023-11-11
  • python定时执行指定函数的方法

    python定时执行指定函数的方法

    这篇文章主要介绍了python定时执行指定函数的方法,涉及Python中sleep方法延时执行的相关使用技巧,需要的朋友可以参考下
    2015-05-05
  • 如何利用python执行txt文件中的代码

    如何利用python执行txt文件中的代码

    这篇文章主要介绍了如何利用python执行txt文件中的代码,python这么强大的语言当然可以做大,只需使用内置的exex()函数,进入主题前我们先来看看什么是exec()函数,需要的小伙伴可以参考一下
    2022-03-03
  • Redis使用watch完成秒杀抢购功能的代码

    Redis使用watch完成秒杀抢购功能的代码

    这篇文章主要介绍了Redis使用watch完成秒杀抢购功能的代码,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧
    2018-05-05
  • python装饰器深入学习

    python装饰器深入学习

    这篇文章主要深入学习了python装饰器的相关资料,什么是装饰器?装饰器遵循的原则等,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • python中可以发生异常自动重试库retrying

    python中可以发生异常自动重试库retrying

    这篇文章主要介绍了python中可以发生异常自动重试库retrying,retrying是一个极简的使用Python编写的库,主题更多相关内容需要的朋友可以参考一下
    2022-06-06
  • 一文带你了解Python协程的详细解释以及例子

    一文带你了解Python协程的详细解释以及例子

    协程不是计算机提供的,计算机只提供:进程、线程。协程是人工创造的一种用户态切换的微进程,使用一个线程去来回切换多个进程,本文就来通过一些示例和大家详细聊聊Python中的协程吧
    2023-03-03
  • 弄懂这56个Python使用技巧(轻松掌握Python高效开发)

    弄懂这56个Python使用技巧(轻松掌握Python高效开发)

    这篇文章主要介绍了弄懂这56个Python使用技巧(轻松掌握Python高效开发),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-09-09
  • Python中pip更新和三方插件安装说明

    Python中pip更新和三方插件安装说明

    本篇文章给大家分享了Python中pip更新和三方插件安装的相关知识点内容,有兴趣的朋友可以参考学习下。
    2018-07-07
  • Python深度学习pytorch神经网络块的网络之VGG

    Python深度学习pytorch神经网络块的网络之VGG

    虽然AlexNet证明深层神经网络卓有成效,但它没有提供一个通用的模板来指导后续的研究人员设计新的网络。下面,我们将介绍一些常用于设计深层神经网络的启发式概念
    2021-10-10

最新评论