2 ##############################################################################
3 # Copyright (c) 2016 Feng Pan (fpan@redhat.com) and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
15 def generate_ip_range(args):
17 Generate IP range in string format for given CIDR.
18 This function works for both IPv4 and IPv6.
20 args is expected to contain the following members:
21 CIDR: any valid CIDR representation.
22 start_position: starting index, default to first address in subnet (1)
23 end_position: ending index, default to last address in subnet (-1)
25 Returns IP range in string format. A single IP is returned if start and end IPs are identical.
27 cidr = ipaddress.ip_network(args.CIDR)
28 (start_index, end_index) = (args.start_position, args.end_position)
29 if cidr[start_index] == cidr[end_index]:
30 return str(cidr[start_index])
32 return ','.join(sorted([str(cidr[start_index]), str(cidr[end_index])]))
39 parser = argparse.ArgumentParser()
40 subparsers = parser.add_subparsers()
42 parser_gen_ip_range = subparsers.add_parser('generate_ip_range', help='Generate IP Range given CIDR')
43 parser_gen_ip_range.add_argument('CIDR', help='Network in CIDR notation')
44 parser_gen_ip_range.add_argument('start_position', type=int, help='Starting index')
45 parser_gen_ip_range.add_argument('end_position', type=int, help='Ending index')
46 parser_gen_ip_range.set_defaults(func=generate_ip_range)
48 args = parser.parse_args(sys.argv[1:])
49 print(args.func(args))
52 if __name__ == '__main__':