string compare question.Please Help!!!

Andreas Kostyrka andreas at mtg.co.at
Sat Feb 16 04:01:45 EST 2002


On Tue, 25 Dec 2001 15:05:21 +1000
"Evgeny Jonson" <john at ablogic.ru> wrote:

> def ip_cmp(ip1, ip2):
>     """Compare IP addreses as strings
>     """
>     l_ip1 = ip1.split('.')
>     l_ip2 = ip2.split('.')
>     if len(l_ip1) == 4 and len(l_ip2) == 4:
>         s_ip1 = string.zfill(l_ip1[0], 3) + '.' + \
>                 string.zfill(l_ip1[1], 3) + '.' + \
>                 string.zfill(l_ip1[2], 3) + '.' + \
>                 string.zfill(l_ip1[3], 3)
>     
>         s_ip2 = string.zfill(l_ip2[0], 3) + '.' + \
>                 string.zfill(l_ip2[1], 3) + '.' + \
>                 string.zfill(l_ip2[2], 3) + '.' + \
>                 string.zfill(l_ip2[3], 3)
>         resault = cmp(s_ip1, s_ip2)
>     else:
>         print 'Wrong IP addres format!'
>         sys.exit(0)
Well, this is obviously wrong. Something like "raise ValueError,"bad ip address "+str(ip1)+" or "+str(ip2) would
appropiate. sys.exit just kills your python process.

But one can do this even easier:
def ip_cmp(a,b):
    a=[int(x) for x in a.split(".",3)]
    b=[int(x) for x in b.split(".",3)]
    return cmp(a,b)

Only caveat, that my ip_cmp doesn't check for adresses are shorter than 4 bytes. All other error cases are
caught directly by the expressions.
>>> ip_cmp("10.66.73.78","10.0")
1
>>> ip_cmp("a.66.73.78","10.0.0.0")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "t.py", line 2, in ip_cmp
    a=[int(x) for x in a.split(".",3)]
ValueError: invalid literal for int(): a>>> ip_cmp("9.66.73.78","10.0.0.0.244")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "t.py", line 3, in ip_cmp
    b=[int(x) for x in b.split(".",3)]
ValueError: invalid literal for int(): 0.244

Andreas







More information about the Python-list mailing list