Merge "updating ONOS build"
[apex.git] / lib / python / apex / ip_utils.py
1
2 ##############################################################################
3 # Copyright (c) 2016 Feng Pan (fpan@redhat.com) and others.
4 #
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 ##############################################################################
10
11
12 import ipaddress
13
14
15 def generate_ip_range(args):
16     """
17     Generate IP range in string format for given CIDR.
18     This function works for both IPv4 and IPv6.
19
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)
24
25     Returns IP range in string format. A single IP is returned if start and end IPs are identical.
26     """
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])
31     else:
32         return ','.join(sorted([str(cidr[start_index]), str(cidr[end_index])]))
33
34
35 def main():
36     import argparse
37     import sys
38
39     parser = argparse.ArgumentParser()
40     subparsers = parser.add_subparsers()
41
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)
47
48     args = parser.parse_args(sys.argv[1:])
49     print(args.func(args))
50
51
52 if __name__ == '__main__':
53     main()
54