0

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
3
  • am I allowed to quote that url or do i need to mask it? Commented Oct 26, 2014 at 9:31
  • I don't know what you mean by that. What is geturldata? Commented Oct 26, 2014 at 9:42
  • geturldata() gets all the data from the url page as a long string with some error checking if the url fails etc... Commented Oct 26, 2014 at 10:00

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.