b8a4d7443d55270954fa9527fae541f8954529c4
[csit.git] / resources / libraries / python / IPAddress.py
1 # Copyright (c) 2020 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Common IP utilities library."""
15
16 from enum import IntEnum
17
18
19 class AddressFamily(IntEnum):
20     """IP address family."""
21     ADDRESS_IP4 = 0
22     ADDRESS_IP6 = 1
23
24
25 class IPAddress:
26     """Common IP address utilities"""
27
28     @staticmethod
29     def union_addr(ip_addr):
30         """Creates union IP address.
31
32         :param ip_addr: IPv4 or IPv6 address.
33         :type ip_addr: IPv4Address or IPv6Address
34         :returns: Union IP address.
35         :rtype: dict
36         """
37         return dict(ip6=ip_addr.packed) if ip_addr.version == 6 \
38             else dict(ip4=ip_addr.packed)
39
40     @staticmethod
41     def create_ip_address_object(ip_addr):
42         """Create IP address object.
43
44         :param ip_addr: IPv4 or IPv6 address
45         :type ip_addr: IPv4Address or IPv6Address
46         :returns: IP address object.
47         :rtype: dict
48         """
49         return dict(
50             af=getattr(
51                 AddressFamily, u"ADDRESS_IP6" if ip_addr.version == 6
52                 else u"ADDRESS_IP4"
53             ).value,
54             un=IPAddress.union_addr(ip_addr)
55         )