我正在尝试使用'GeoIP2-City '查找给定IP地址的国家名称。mmdb的文件。
示例:IP: 24.171.221.56,我需要得到"Puerto Rico"。但是当我在函数中传递IP地址时,这不起作用。
ipa = ['24.171.221.56']
def country(ipa, reader):
try:
response = reader.city(ipa)
response = response.country.name
return response
except:
return 'NA'
country(ipa, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))
'NA'
但是,如果我在函数中使用实际的IP地址,它将返回'Puerto Rico'
ipa = ['24.171.221.56']
def country(ipa, reader):
try:
response = reader.city('24.171.221.56')
response = response.country.name
return response
except:
return 'NA'
country(ipa, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))
'Puerto Rico'
有人能帮忙吗?
首先,您需要将ip作为字符串传递,而不是作为列表传递,因为您的函数只被设计为返回一个ip的位置:
ip = '24.171.221.56'
第二,它应该是ip
,而不是ipa
。你的函数参数必须匹配你在里面使用的变量,你发送的参数必须匹配你在外面定义的。最好将它们全部标准化为ip
。
ip = '24.171.221.56'
def country(ip, reader):
try:
response = reader.city(ip)
response = response.country.name
return response
except:
return 'NA'
country(ip, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))
如果你打算为多个ip这样做,你可以在一个列表中定义它们,但是你必须为列表中的每个项目调用一次函数:
reader=geoip2.database.Reader('GeoIP2-City.mmdb')
ips=['24.171.221.56','24.171.221.57']
for ip in ips:
country(ip, reader=reader)
您可以尝试下面的代码片段。
代码:
import geoip2.database as ip_db
ip_list = ['24.171.221.56', '81.212.104.158', '90.183.159.46']
def country(ip_list, reader):
country_dict = {}
for ip in ip_list:
try:
response = reader.city(ip)
country = response.country.name
country_dict[ip] = country
except:
country_dict[ip] = 'NA'
return country_dict
print(country(ip_list, reader=ip_db.Reader('GeoIP2-City.mmdb')))
输出:
{'24.171.221.56': 'Puerto Rico', '81.212.104.158': 'Turkey', '90.183.159.46': 'Czechia'}
将列表传递给函数,因此需要执行ip[0]或在函数内部更改它以使用列表
行内:
response = reader.city(ip)
ip没有定义