11#!/usr/bin/python3
22import fcntl
33import glob
4+ import ipaddress
45import json
56import logging
67import os
@@ -216,6 +217,8 @@ def wait_until_all_interfaces_are_connected(interfaces: int) -> None:
216217 time .sleep (1 )
217218
218219
220+ # This function works only for IPv4 interfaces.
221+ # See: man 7 netdevice
219222def get_ip_address (iface : str ) -> str :
220223 # Source: https://bit.ly/3dROGBN
221224 s = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
@@ -226,6 +229,20 @@ def get_ip_address(iface: str) -> str:
226229 )[20 :24 ])
227230
228231
232+ # This function works only for IPv4 interfaces
233+ # See: man 7 netdevice
234+ def get_netmask (iface : str ) -> str :
235+ s = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
236+ netmask = socket .inet_ntoa (fcntl .ioctl (
237+ s .fileno (),
238+ 0x891b , # SIOCGIFNETMASK
239+ struct .pack ('256s' , iface .encode ('utf-8' ))
240+ )[20 :24 ])
241+ return str (ipaddress .ip_network (f"0.0.0.0/{ netmask } " ).prefixlen )
242+
243+
244+ # This function works only for IPv4 interfaces
245+ # Set: man 7 netdevice
229246def get_mac_address (iface : str ) -> str :
230247 s = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
231248 mac = fcntl .ioctl (
@@ -236,6 +253,7 @@ def get_mac_address(iface: str) -> str:
236253 return ':' .join ('%02x' % b for b in mac )
237254
238255
256+ # This function works only for IPv4 interfaces
239257def get_default_gateway () -> str :
240258 # Source: https://splunktool.com/python-get-default-gateway-for-a-local-interfaceip-address-in-linux
241259 with open ("/proc/net/route" ) as fh :
@@ -284,6 +302,7 @@ def parse_port_config() -> dict[str, dict]:
284302
285303
286304def create_config_db (hwsku : str ) -> dict :
305+ mgmt_interface_cidr = get_ip_address ("eth0" ) + "/" + get_netmask ("eth0" )
287306 return {
288307 'AUTO_TECHSUPPORT' : {
289308 'GLOBAL' : {
@@ -315,7 +334,7 @@ def create_config_db(hwsku: str) -> dict:
315334 }
316335 },
317336 'MGMT_INTERFACE' : {
318- f'eth0|{ get_ip_address ( "eth0" ) } /16 ' : {
337+ f'eth0|{ mgmt_interface_cidr } ' : {
319338 'gwaddr' : get_default_gateway (),
320339 }
321340 },
0 commit comments