Reputation: 99
I have following function that gives me errors. It should extract the IP from the website url Sometimes it works sometimes i get following error:
File "test.py", line 30, in getIPextA
address = grab[0] # get address as a string
IndexError: list index out of range
Function:
def getIPextA():
"""
Version A Get external ip from "http://checkip.dyndns.org/"
"""
site=geturldata("http://checkip.dyndns.org/")
if site =="" : return [0,0,0,0]
grab = re.findall('\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3}',site)
address = grab[0] # get address as a string
return map(int,address.split('.')) # as an integer list
Upvotes: 0
Views: 123
Reputation: 126722
I suggest something like this instead
match = re.search(r' (\d{1,3}) \. (\d{1,3}) \. (\d{1,3}) \. (\d{1,3}) ', site, flags=re.X)
return match.groups() if match else [0, 0, 0, 0]
which allows between one and three digits in each octet, and has the dots .
escaped properly as well. The flags
parameter allows me to add insignificant whitespace so that the regex is more readable. Each octet is cointained in parentheses, so the MatchObject
will return a list of four decimal strings if you call its groups
method.
But I don't know what your geturldata
function is so I can't help any more.
Upvotes: 0
Reputation: 6390
You get the error when the IP address could not match the regex. The reason is probably that you sometimes have an IP containing a one-digit part. These are also valid IPs. You should also escape the dot, because a dot in a regex means that it can match any char.
grab = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',site)
Upvotes: 1