Get the hardware address on Windows by running ipconfig.exe.
544793
def _ipconfig_getnode():
    """"""
    import os, re
    dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
    try:
        import ctypes
        buffer = ctypes.create_string_buffer(300)
        ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)  # @UndefinedVariable
        dirs.insert(0, buffer.value.decode('mbcs'))
    except:
        pass
    for dir in dirs:
        try:
            pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
        except IOError:
            continue
        for line in pipe:
            value = line.split(':')[-1].strip().lower()
            if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
                return int(value.replace('-', ''), 16)
1013514
def RetrieveIP4Info(self, ip):
    """"""
    if ip.is_private:
      return (IPInfo.INTERNAL, "Internal IP address.")
    try:
      # It's an external IP, let's try to do a reverse lookup.
      res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)
      return (IPInfo.EXTERNAL, res[0])
    except (socket.error, socket.herror, socket.gaierror):
      return (IPInfo.EXTERNAL, "Unknown IP address.")
954346
def _get_ipv4_addrs(self):
        
        addrs = self._get_addrs()
        ipv4addrs = addrs.get(netifaces.AF_INET)
        if not ipv4addrs:
            return {}
        return ipv4addrs[0]
1095568
def dns_dhcp(name, interface='Local Area Connection'):
    '''
    
    '''
    ret = {'name': name,
           'result': True,
           'changes': {},
           'comment': ''}

    # Check the config
    config = __salt__['win_dns_client.get_dns_config'](interface)
    if config == 'dhcp':
        ret['comment'] = '{0} already configured with DNS from DHCP'.format(
                interface)
        return ret
    else:
        ret['changes'] = {'dns': 'configured from DHCP'}

    if __opts__['test']:
        ret['result'] = None
        return ret

    # change the configuration
    ret['result'] = __salt__['win_dns_client.dns_dhcp'](interface)
    if not ret['result']:
        ret['changes'] = {}
        ret['comment'] = (
                'Could not configure "{0}" DNS servers from DHCP'
                ).format(interface)

    return ret
233197
def get_alias_address(iface_name, ip_mask, gw_str, metric):
    

    # Detect the architecture
    if scapy.consts.IS_64BITS:
        offset, name_len = 16, 40
    else:
        offset, name_len = 32, 32

    # Retrieve interfaces structures
    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', b'\0' * 4096)
    ifreq = ioctl(sck.fileno(), SIOCGIFCONF,
                  struct.pack("iL", len(names), names.buffer_info()[0]))

    # Extract interfaces names
    out = struct.unpack("iL", ifreq)[0]
    names = names.tobytes() if six.PY3 else names.tostring()
    names = [names[i:i + offset].split(b'\0', 1)[0] for i in range(0, out, name_len)]  # noqa: E501

    # Look for the IP address
    for ifname in names:
        # Only look for a matching interface name
        if not ifname.decode("utf8").startswith(iface_name):
            continue

        # Retrieve and convert addresses
        ifreq = ioctl(sck, SIOCGIFADDR, struct.pack("16s16x", ifname))
        ifaddr = struct.unpack(">I", ifreq[20:24])[0]
        ifreq = ioctl(sck, SIOCGIFNETMASK, struct.pack("16s16x", ifname))
        msk = struct.unpack(">I", ifreq[20:24])[0]

        # Get the full interface name
        ifname = plain_str(ifname)
        if ':' in ifname:
            ifname = ifname[:ifname.index(':')]
        else:
            continue

        # Check if the source address is included in the network
        if (ifaddr & msk) == ip_mask:
            sck.close()
            return (ifaddr & msk, msk, gw_str, ifname,
                    scapy.utils.ltoa(ifaddr), metric)

    sck.close()
    return
774983
def get_ip_info(ip_str):
    
    ip = None
    is_routable_ip = False
    if is_valid_ip(ip_str):
        ip = ip_str
        is_routable_ip = is_public_ip(ip)
    return ip, is_routable_ip
958545
function findSystemPortRange() {
  if (systemRange) {
    return systemRange;
  }
  var range = process.platform === 'win32' ?
      findWindowsPortRange() : findUnixPortRange();
  return systemRange = range.thenCatch(function() {
    return DEFAULT_IANA_RANGE;
  });
}
690694
def getallhwinfo():
    """"""
    hwinfo = meminfo()
    hwinfo.update(cpuinfo())
    hwinfo.update(uname())
    hwinfo.update(vgadata())
    hwinfo.update(distro())
    hwinfo.update(diskdata())
    hwinfo.update(hostname())
    hwinfo.update(serial_number())
    ip = ip_address()
    hwinfo.update(mac_address(ip))
    hwinfo.update({'IP': ip})
    hwinfo.update(system_model())
    return hwinfo
949948
def read_registry(self):
        """"""
        lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
        want_scan = False
        try:
            try:
                # XP, 2000
                tcp_params = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\Tcpip\Parameters')
                want_scan = True
            except EnvironmentError:
                # ME
                tcp_params = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\VxD\MSTCP')
            try:
                self._config_win32_fromkey(tcp_params)
            finally:
                tcp_params.Close()
            if want_scan:
                interfaces = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\Tcpip\Parameters'
                                             r'\Interfaces')
                try:
                    i = 0
                    while True:
                        try:
                            guid = _winreg.EnumKey(interfaces, i)
                            i += 1
                            key = _winreg.OpenKey(interfaces, guid)
                            if not self._win32_is_nic_enabled(lm, guid, key):
                                continue
                            try:
                                self._config_win32_fromkey(key)
                            finally:
                                key.Close()
                        except EnvironmentError:
                            break
                finally:
                    interfaces.Close()
        finally:
            lm.Close()
34553
def local_ip():
    """"""
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith('127.'):
        # Check eth0, eth1, eth2, en0, ...
        interfaces = [
            i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
        ]  # :(
        for interface in interfaces:
            try:
                ip = interface_ip(interface)
                break
            except IOError:
                pass
    return ip
874575
def getLocalIPaddress():
    """"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('google.com', 0))
        my_local_ip = s.getsockname()[0] # takes ~0.005s
        #from netifaces import interfaces, ifaddresses, AF_INET
        #full solution in the event of multiple NICs (network interface cards) on the PC
        #def ip4_addresses():
        #    ip_list = []
        #    for interface in interfaces():
        #        for link in ifaddresses(interface)[AF_INET]: # If IPv6 addresses are needed instead, use AF_INET6 instead of AF_INET
        #            ip_list.append(link['addr'])
        #    return ip_list
    except Exception:
        my_local_ip = None
    return my_local_ip
240112
def get_nic_mtu(nic):
    """"""
    cmd = ['ip', 'addr', 'show', nic]
    ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
    mtu = ""
    for line in ip_output:
        words = line.split()
        if 'mtu' in words:
            mtu = words[words.index("mtu") + 1]
    return mtu
201517
def get_dns_servers(interface='Local Area Connection'):
    '''
    
    '''
    # remove any escape characters
    interface = interface.split('\\')
    interface = ''.join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapter(NetEnabled=True):
            if interface == iface.NetConnectionID:
                iface_config = c.Win32_NetworkAdapterConfiguration(Index=iface.Index).pop()
                try:
                    return list(iface_config.DNSServerSearchOrder)
                except TypeError:
                    return []
    log.debug('Interface "%s" not found', interface)
    return False
952467
def get_ip_address(ifname):
    
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])
985342
def get_hardware_router_type_id(self, context):
        """"""
        cctxt = self.client.prepare()
        return cctxt.call(context,
                          'get_hardware_router_type_id',
                          host=self.host)
464241
def _detect(self):
        """"""
        theip = None
        try:
            if self.opts_family == AF_INET6:
                addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6]
            else:
                addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET]
        except ValueError as exc:
            LOG.error("netifaces choked while trying to get network interface"
                      " information for interface '%s'", self.opts_iface,
                      exc_info=exc)
        else:  # now we have a list of addresses as returned by netifaces
            for pair in addrlist:
                try:
                    detip = ipaddress(pair["addr"])
                except (TypeError, ValueError) as exc:
                    LOG.debug("Found invalid IP '%s' on interface '%s'!?",
                              pair["addr"], self.opts_iface, exc_info=exc)
                    continue
                if self.netmask is not None:
                    if detip in self.netmask:
                        theip = pair["addr"]
                    else:
                        continue
                else:
                    theip = pair["addr"]
                break  # we use the first IP found
        # theip can still be None at this point!
        self.set_current_value(theip)
        return theip
1238357
def get_ip(self, use_cached=True):
        """"""
        device_json = self.get_device_json(use_cached)
        return device_json.get("dpLastKnownIp")