IP Address in Python (Windows)

From StackOverflow, my changes:

  • Py3 compat (no big deal)
  • Added DHCP support
  • Use CurrentControlSet (saner IMHO)
import os
import sys
import winreg as _winreg # Hack for py3 compared to original SO post


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 range(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\CurrentControlSet\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")
        if ['0.0.0.0'] == subnet_mask:
            (subnet_mask, type_) = _winreg.QueryValueEx(adapter_service_key, "DhcpSubnetMask")
            if _winreg.REG_SZ == type_:
                subnet_mask = [subnet_mask] # Make 1-element list to match non-DHCP
        (ip_address, _) = _winreg.QueryValueEx(adapter_service_key, "IpAddress")
        if ['0.0.0.0'] == ip_address:
            (ip_address, type_) = _winreg.QueryValueEx(adapter_service_key, "DhcpIPAddress")
            if _winreg.REG_SZ == type_:
                ip_address = [ip_address] # Make 1-element list to match non-DHCP
        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()

Comments

No comments.