Skip to content
Advertisement

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

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?

Advertisement

Answer

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'}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement