我有一个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)
和这个问题有点无关,但重新发明轮子让我大吃一惊。或者你可以使用免费的学习版(或者是免费的学习版)。代码是稳定的,经过测试,可以在生产中使用。在
示例:
要求:
相关:
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的数字版本进行比较。在
您可以在处理IP地址时使用库netaddr。在
然后您可以使用类似于:
注意:以下代码未经测试,因为我没有您的数据。您可能需要进行一些小的更改才能实际运行代码。如果你在运行这个程序时遇到任何错误,把它贴在这里,我会努力纠正。在
^{pr2}$相关问题 更多 >
编程相关推荐