[Tutor] print IP address range to stdout

Alan Plum alan.plum at uni-koeln.de
Tue Dec 22 12:46:34 CET 2009


On Di, 2009-12-22 at 10:53 +0100, MK wrote:
> Here is my program so far:
> <snip>

Please translate comments if you post to an English list. Not everyone
speaks German.

> The start_adress and end_adress are the ip-range.
> 
> For example:
> printdomains.py -s 192.168.178.0 -e 193.170.180.4
> 
> This should make all ips and stop at the end_adress.

IP addresses consist of four blocks of values between 0 and 255
(inclusive). This means they can easily be translated into a hexadecimal
value: 255.255.255.0 is ff.ff.ff.00 or 0xffffff00.

Knowing this, you could simplify the problem:

each block of the start address is offset by 8 bits from the next, so we
can do something like this:

# Translate the start address blocks into integers:
start_blocks = [int(block) for block in start_address.split('.')]

# Now offset the blocks and add them together:
start = 0
for k, block in enumerate(start_blocks):
    start += block << (8 * k)

# Do the same for the end address:
end_blocks = [int(block) for block in end_address.split('.')]
end = 0
for k, block in enumerate(end_blocks):
    end += block << (8 * k)

# Now generate the addresses:
for ip in range(start, end+1):
    blocks = []
    for i in range(4):
        blocks.append((ip & (0xff << (8 * i))) >> (8 * i))
    print '.'.join(blocks)

Hope this helps. I haven't run this code, so you might want to make sure
it works correctly before using it.

Cheers,

Alan Plum



More information about the Tutor mailing list