Passing IP address isn't working in a Function, unless I explicitly mention it

Viewed 75

I'm trying to find the Country name for the given IP address using the 'GeoIP2-City.mmdb' file.

Ex: IP: 24.171.221.56, I need to get 'Puerto Rico'. But this isn't working when I passed the IP address in a function.

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'

However, If I use the actual IP address in the function it is returning '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'

Can someone help with this?

4 Answers

First, you need to pass the ip as a string, not as a list, since your function is only designed to return the location of one IP:

ip = '24.171.221.56'

Second, it should be ip, not ipa. Your function argument must match the variable you're using inside it, and the argument you send must match what you've defined outside. It's best to standardize them all to 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'))

If you were intending to do this for multiple ips, you can define them in a list, but then you have to call the function once for each item in the list:

reader=geoip2.database.Reader('GeoIP2-City.mmdb')
ips=['24.171.221.56','24.171.221.57']
for ip in ips:
    country(ip, reader=reader)

You pass a list to the function, so you need to do ip[0] or change it inside the function to use lists

In line:

response = reader.city(ip)

ip is not defined.

You can try the following code snippet.

Code:

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')))

Output:

{'24.171.221.56': 'Puerto Rico', '81.212.104.158': 'Turkey', '90.183.159.46': 'Czechia'}
Related