返回IP地址的国家代码

2024-09-27 09:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,其中IP范围与土地代码一起存储:

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"

可以这样理解:

^{pr2}$

当用户要求一个特定的IP地址时,我想把这个IP对应的国家代码返回给他。例如,1.0.9.10将返回中国的CN,因为它介于1.0.8.0和{}之间

我不知道该怎么处理。以下是我目前所做的,但我怀疑我的方向是正确的:

import csv

with open("GeoIPCountryWhois.csv") as csvfile:

readCSV = csv.reader(csvfile, delimiter = ",")

IP_LOWs = []
IP_HIGHs = []
Land_CODEs = []
Lands = []

for row in readCSV:
    IP_LOW = row[0]
    IP_HIGH = row[1]
    Land_CODE = row[4]
    Land = row[5]

    IP_LOWs.append(IP_LOW)
    IP_HIGHs.append(IP_HIGH)
    Land_CODEs.append(Land_CODE)
    Lands.append(Land)

whatIP = input("What IP should be looked up? ")

codedex = IP_LOWs.index(whatIP)
landdex = Lands.index(whatIP)
IP_to_Code = Land_CODE[codedex]
IP_to_land = Land[landdex]

print(IP_to_Code)
print(IP_to_land)

Tags: csvto代码ipcodecnrowau
3条回答

和这个问题有点无关,但重新发明轮子让我大吃一惊。或者你可以使用免费的学习版(或者是免费的学习版)。代码是稳定的,经过测试,可以在生产中使用。在

示例:

#
from pygeoip import GeoIP, MEMORY_CACHE
#
try:
    import win_inet_pton#patches socket library for Windows use
except ImportError:
    pass
import socket

###############################################################################

def is_valid_ipv4(ip_str):
    """
    Check the validity of an IPv4 address
    """
    try:
        socket.inet_pton(socket.AF_INET, ip_str)#@UndefinedVariable
    except AttributeError:
        try:
            socket.inet_aton(ip_str)
        except socket.error:
            return False
        return ip_str.count('.') == 3
    except socket.error:
        return False
    return True

def is_valid_ipv6(ip_str):
    """
    Check the validity of an IPv6 address
    """
    try:
        socket.inet_pton(socket.AF_INET6, ip_str)#@UndefinedVariable
    except socket.error:
        return False
    return True

###############################################################################

def get_country_from_ip(ip):

    geo_record = None

    if is_valid_ipv4(ip):
        geo_country_ipv4_db = GeoIP('[path/to/dat/file]GeoLiteCity.dat', MEMORY_CACHE)
        geo_record = geo_country_ipv4_db.record_by_addr(ip)

    if is_valid_ipv6(ip):
        geo_country_ipv6_db = GeoIP('[path/to/dat/file]GeoLiteCityv6.dat', MEMORY_CACHE)
        geo_record = geo_country_ipv6_db.record_by_addr(ip)

    if geo_record:
        return geo_record.get('country_code', '').lower()

    return None

###############################################################################

print get_country_from_ip('1.0.9.10')

要求:

相关:

Regexp to check if an IP is valid

安装所需的扩展名,替换“[path/to/dat/file]”就完成了。在

使用Convert an IP string to a number and vice versa中的代码,可以将输入IP转换为数字。然后您可以将其与CSV第3列和第4列中的起始/结束IP的数字版本进行比较。在

import csv

with open("GeoIPCountryWhois.csv") as csvfile:

    readCSV = csv.reader(csvfile, delimiter = ",")

    GeoIPs = []

    for row in readCSV:
        GeoIPs.append({ low: row[2], high: row[3], land_code: row[4], land: row[5] })

    whatIP = input("What IP should be looked up? ")
    whatIP_long = ip2long(whatIP)        
    found_range = next((GeoIP for GeoIP in GeoIPs if GeoIP.low <= whatIP_long <= GeoIP.high), None)
    if found_range:
        IP_to_Code = found_range.land_code
        IP_to_land = found_range.land

    print(IP_to_Code)
    print(IP_to_land)

您可以在处理IP地址时使用库netaddr。在

from netaddr import *
IPAddress("1.0.3.255")>IPAddress("1.1.2.1")
#False

然后您可以使用类似于:

注意:以下代码未经测试,因为我没有您的数据。您可能需要进行一些小的更改才能实际运行代码。如果你在运行这个程序时遇到任何错误,把它贴在这里,我会努力纠正。在

^{pr2}$

相关问题 更多 >

    热门问题