1
1
import ipaddress
2
2
import json
3
-
4
- from ipaddress import IPv4Interface , IPv4Network , IPv4Address
3
+ from ipaddress import IPv4Address , IPv4Interface , IPv4Network
5
4
from typing import Dict
6
5
7
6
@@ -14,12 +13,16 @@ def __init__(self, ipaddr_db_json_path: str):
14
13
self .json_path = ipaddr_db_json_path
15
14
self ._ip_version = 4
16
15
self ._prefix_len = 0
17
- self ._ipaddr_pool = {}
16
+ self ._ipaddr_pool = []
17
+ self ._hostnames = {}
18
18
self ._load_from_json (ipaddr_db_json_path )
19
19
20
20
@property
21
21
def addresses (self ):
22
- addresses = list (self ._ipaddr_pool .keys ())
22
+ addresses = list (self ._ipaddr_pool )
23
+ addresses .extend (self ._hostnames .keys ())
24
+ addresses .sort ()
25
+
23
26
return addresses
24
27
25
28
def is_initialized (self ):
@@ -32,25 +35,44 @@ def initialize(self, ipv4_cidr_address: str):
32
35
33
36
prefix_len , address_list = self ._generate_addresses (ipv4_cidr_address )
34
37
35
- for addr in address_list :
36
- self ._ipaddr_pool [addr ] = None
37
-
38
+ self ._ipaddr_pool = address_list
38
39
self ._prefix_len = prefix_len
39
40
self ._save ()
40
41
41
42
def _to_dict (self ):
42
43
_dict = {
43
44
"ip_version" : self ._ip_version ,
44
45
"network_prefix_len" : self ._prefix_len ,
45
- "addresses" : {str (k ): v for k , v in self ._ipaddr_pool .items ()}
46
+ "unused_addresses" : [str (k ) for k in self ._ipaddr_pool ],
47
+ "hostnames" : {k : str (v ) for k , v in self ._hostnames .items ()},
46
48
}
49
+
47
50
return _dict
48
51
49
52
def _initialize_from_dict (self , ip_pool_dict : Dict ):
50
53
self ._ip_version = ip_pool_dict ["ip_version" ]
51
54
self ._prefix_len = ip_pool_dict ["network_prefix_len" ]
52
- addrs = ip_pool_dict ["addresses" ]
53
- self ._ipaddr_pool = {IPv4Address (k ): v for k , v in addrs .items ()}
55
+ unused_addrs = ip_pool_dict ["unused_addresses" ]
56
+ hostnames = ip_pool_dict ["hostnames" ]
57
+
58
+ pool = []
59
+ # hostnames = {}
60
+
61
+ for addr_str in unused_addrs :
62
+ addr = IPv4Address (addr_str )
63
+ pool .append (addr )
64
+
65
+ for hostname , addr_str in hostnames .items ():
66
+ addr = IPv4Address (addr_str )
67
+ if addr in hostnames .values ():
68
+ dupes = [hostname , hostnames [addr ]]
69
+ raise IPAddressPoolException (
70
+ f"Address [{ addr_str } ] used more than once: { dupes } "
71
+ )
72
+ hostnames [hostname ] = addr
73
+
74
+ self ._hostnames = hostnames
75
+ self ._ipaddr_pool = pool
54
76
55
77
def _save (self ):
56
78
save_dict = self ._to_dict ()
0 commit comments