summaryrefslogtreecommitdiff
path: root/src/system/normalize-ip
blob: 08f922a8e557750ed5b1d13f2dbb82be156e2eae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
#
# Copyright (C) 2018 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#

# Normalizes IPv6 addresses so that they can be passed to iproute2,
# since iproute2 will not take an address with leading zeroes for an argument

import re
import sys
import ipaddress


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Argument required")
        sys.exit(1)

    address_string, prefix_length = re.match(r'(.+)/(.+)', sys.argv[1]).groups()

    try:
        address = ipaddress.IPv6Address(address_string)
        normalized_address = address.compressed
    except ipaddress.AddressValueError:
        # It's likely an IPv4 address, do nothing
        normalized_address = address_string

    print("{0}/{1}".format(normalized_address, prefix_length))
    sys.exit(0)