I recently had to write a bit of code to enumerate all IPv6 addresses in a given range. The syntax allows for the use of "*" and "-", where "*" is semantically equivalent to "0-ffff". Here's my quick and dirty solution. I also thought it was interesting because I used some python constructs you don't see very often and a recursive generator,
def expand_ipv6(addr_range): # first change all '*' portions to use '-' addr_range = map(lambda part: '0-ffff' if part == '*' else part, addr_range.split(':')) addr_range.reverse() # stackify for addr in expand_part(, addr_range): yield ':'.join(addr) + '\n' def expand_part(prefix, remainder): "recursively expand an address given a prefix (list) and remainder (stack)" current = remainder.pop() if '-' not in current: # if the current part is not a range, add to the prefix and continue if remainder: for addr in expand_part(prefix + [current], remainder[:]): yield addr else: yield prefix + [current] else: # expand the range current = current.split('-') for i in xrange(int(current, 16), int(current, 16)+1): if remainder: for addr in expand_part(prefix + [hex(i)[2:]], remainder[:]): yield addr else: yield prefix + [hex(i)[2:]]
Generators are important because a range could expand to a HUGE number of IPv6 addresses and you wouldn't want to try to generate them all and store them in memory. Just one "*" yields 65,536 addresses, and using multiple "*" or "-" ranges means you're multiplying that number.