Home > other >  Python GeoIP2 AddressNotFoundError
Python GeoIP2 AddressNotFoundError

Time:01-10

Im trying to use Python GeoIP to convert IP address to Geo details using Maxmind Database.

import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
        response = db.city(line.strip())
        print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude

Im getting the error "geoip2.errors.AddressNotFoundError: The address 103.229.234.197 is not in the database."

    Traceback (most recent call last):
  File "script.py", line 14, in <module>
    response = db.city(line.strip())
  File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 110, in city
    return self._model_for(geoip2.models.City, 'City', ip_address)
  File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 180, in _model_for
    record = self._get(types, ip_address)
  File "/usr/lib/python2.7/site-packages/geoip2/database.py", line 176, in _get
    "The address %s is not in the database." % ip_address)
geoip2.errors.AddressNotFoundError: The address 103.229.234.197 is not in the database.

Maxmind db mentions as the address not in database. However its not going to hurt me but how can a ignore this error and get my output of which ever is available?

Tried to except any error (although not a best way) and also to expect particular AddressNotFoundError.

try:
     print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude
except:
       pass

also,

try:
     print line.strip(), response.country.name, response.country.iso_code, response.location.longitude, response.location.latitude

except AddressNotFoundError:
     pass

Still no luck.

Any suggestions.

CodePudding user response:

The problem here is the exception happening in db.city call, not in values printing, so you could try this:

import urllib2
import csv
import geoip2.database
db = geoip2.database.Reader("GeoLite2-City.mmdb")
target_url="http://myip/all.txt"
data = urllib2.urlopen(target_url)
for line in data:
    try:
        response = db.city(line.strip())
        print line.strip(), response.country.name, response.country.iso_code, response.location.longitude,   response.location.latitude
    exception:
        pass
  • Related