Øyvind wrote: > Hello. > > I have a database where I have some IP-ranges. Then I have some logs over > IPs from customers and need to connect the two. > > So, for example: > > Range 1: > 123.132.122.4-123.132.122.255 > > How do I check if IP 123.132.122.58 is a part of that? I have thought > about 4 if statements: > > split(.) > if ip[0] in iprange_from[0] and iprange_to[0]: > if ip[1] in iprange_from[1] and iprange_to[1]: > if ip[2] in iprange_from[2] and iprange_to[2]: > if ip[3] in iprange_from[3] and iprange_to[3]: > then ok > > But that seems silly. Is there some better way?
If the IPs are stored as lists or tuples of integers you can compare them directly and Python will do the right thing. If they are strings, a simple helper function can convert them to lists: In [1]: def ipStrToList(ip): ...: return map(int, ip.split('.')) ...: In [2]: ipStrToList('123.132.122.4') Out[2]: [123, 132, 122, 4] In [3]: lower = _ In [4]: upper = ipStrToList('123.132.122.255') In [5]: lower <= ipStrToList('123.132.122.58') <= upper Out[5]: True In [6]: lower <= ipStrToList('123.132.123.58') <= upper Out[6]: False Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor