Retrieving network mask in Python

前端 未结 8 960
不知归路
不知归路 2021-01-05 07:59

How would one go about retrieving a network device\'s netmask (In Linux preferably, but if it\'s cross-platform then cool)? I know how in C on Linux but I can\'t find a way

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-05 08:03

    In Windows this piece of code may be useful:

    import os
    import sys
    import _winreg
    
    
    def main():
        adapter_list_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
            r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards')
    
        adapter_count = _winreg.QueryInfoKey(adapter_list_key)[0]
    
        for i in xrange(adapter_count):
            sub_key_name = _winreg.EnumKey(adapter_list_key, i)
            adapter_key = _winreg.OpenKey(adapter_list_key, sub_key_name)
            (adapter_service_name, _) = _winreg.QueryValueEx(adapter_key, "ServiceName")
            (description, _) = _winreg.QueryValueEx(adapter_key, "Description")
    
            adapter_registry_path = os.path.join(r'SYSTEM\ControlSet001\Services',
                adapter_service_name, "Parameters", "Tcpip")
            adapter_service_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                adapter_registry_path)
            (subnet_mask, _) = _winreg.QueryValueEx(adapter_service_key, "SubnetMask")
            (ip_address, _) = _winreg.QueryValueEx(adapter_service_key, "IpAddress")
    
            sys.stdout.write("Name: %s\n" % adapter_service_name)
            sys.stdout.write("Description: %s\n" % description)
            sys.stdout.write("SubnetMask: %s\n" % subnet_mask)
            sys.stdout.write("IpAdress: %s\n" % ip_address)
    
    
    if __name__ == "__main__":
        main()
    

    Get network adapters list from HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards registry key and than extract more info about each adapter from HKLM\SYSTEM\ControlSet001\Services\{adapter_guid}\Parameters\Tcpip key.

    I test it on Windows XP with 2 virtual adapters, it works fine. Should work in 2000, 2003, and Vista too.

提交回复
热议问题