Liam Clarke wrote:
Hi, you could save yourself some hassle and do


minipstr = '1.0.0.1'
maxipstr = '1.0.15.16'

minip = map(int, minipstr.split('.'))
maxip = map(int, maxipstr.split('.'))

iplist = []

for a in range(minip[2], maxip[2]+1):

... if a < maxip[2]: ... for b in range(minip[3], 255): ... iplist.append('.'.join(map(str, [minip[0],minip[1], a, b]))) ... else: ... for b in range(minip[3], minip[3]+1): ... iplist.append('.'.join(map(str, [minip[0],minip[1], a, b])))

Eek, that's a bit Perlish, might want to break the iplist.append line into

ipintlist =  [minip[0],minip[1], a, b]
ipstrlist = map(str, ipintlist)
iplist.append('.'.join(ipstrlist))

I don't think this will work correctly with for example minipstr = '1.0.0.1' maxipstr = '1.2.0.0'

I would break this problem up conceptually. It has maybe four different parts:
- convert a string representation of an IP address to a useful representation. Liam shows how to do this above, a list of ints is easy to work with.
- convert the useful representation back to a string. Again, Liam shows how to do this.
- compare two IPs. If the IPs are represented as lists of ints, you can compare them directly:
>>> a=[1,2,1,5]
>>> b=[1,2,3,4]
>>> a>b
False
>>> a<b
True
>>> a==[1,2,1,5]
True


- increment an IP. This is the hardest part. You have to implement a counter that works with the list representation. Here is one way to do it - this function does the right thing with the last 'digit', then if there was a carry it calls itself recursively to increment the next digit. It rolls over from [255, 255, 255, 255] to [0, 0, 0, 0]:

def incr(n, limit, ix=None):
  ''' Increment a number base (limit+1) represented as a list of ints '''
  if ix is None:    # initial call starts at the end
    ix = len(n) - 1
  if ix < 0:        # Off the end, give up
    return
  if n[ix] < limit: # Normal increment
    n[ix] += 1
  else:             # Increment with carry
    n[ix] = 0
    incr(n, limit, ix-1)


a=[1,2,1,5] incr(a, 255) print a

a=[1,2,1,255]
incr(a, 255)
print a

a=[1,2,255,255]
incr(a, 255)
print a

a=[1,255,255,255]
incr(a, 255)
print a

a=[255,255, 255,255]
incr(a, 255)
print a

## prints
[1, 2, 1, 6]
[1, 2, 2, 0]
[1, 3, 0, 0]
[2, 0, 0, 0]
[0, 0, 0, 0]

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to