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

Time:05-06

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(ip)
        response = response.country.name
        return response
    except:
        return 'NA'

country(ip, 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(ip, reader=geoip2.database.Reader('GeoIP2-City.mmdb'))

'Puerto Rico'

Can someone help with this?

CodePudding user response:

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

CodePudding user response:

In line:

response = reader.city(ip)

ip is not defined.

CodePudding user response:

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