Return all Windows Adapters addresses from iphlpapi
551941
def GetAdaptersAddresses(AF=AF_UNSPEC):
    """"""
    # We get the size first
    size = ULONG()
    flags = GAA_FLAG_INCLUDE_PREFIX
    res = _GetAdaptersAddresses(AF, flags,
                                None, None,
                                byref(size))
    if res != 0x6f:  # BUFFER OVERFLOW -> populate size
        raise RuntimeError("Error getting structure length (%d)" % res)
    # Now let's build our buffer
    pointer_type = POINTER(IP_ADAPTER_ADDRESSES)
    buffer = create_string_buffer(size.value)
    AdapterAddresses = ctypes.cast(buffer, pointer_type)
    # And call GetAdaptersAddresses
    res = _GetAdaptersAddresses(AF, flags,
                                None, AdapterAddresses,
                                byref(size))
    if res != NO_ERROR:
        raise RuntimeError("Error retrieving table (%d)" % res)
    results = _resolve_list(AdapterAddresses)
    del(AdapterAddresses)
    return results
830098
def _find_adapter(registry, ob):
    """"""
    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
    for t in types:
        if t in registry:
            return registry[t]
1026400
def _assemble_devinfo(self):
        '''
        
        '''
        devtype = {}
        for p in pcap_devices():
            if p.isloop:
                devtype[p.name] = InterfaceType.Loopback
            else:
                if sys.platform == 'linux':
                    st,output = subprocess.getstatusoutput(["iwconfig", p.name])
                    if "no wireless extensions" in output:
                        devtype[p.name] = InterfaceType.Wired
                    else:
                        devtype[p.name] = InterfaceType.Wireless
                elif sys.platform == 'darwin':
                    devtype[p.name] = InterfaceType.Unknown
                else:
                    devtype[p.name] = InterfaceType.Unknown

        devinfo = {}
        ifinfo = net_if_addrs()
        for devname in self._devs:
            ifaddrs = ifinfo.get(devname, None)
            if ifaddrs is None:
                log_warn("Address info for interface {} not found! (skipping)".format(devname))

            if sys.platform == 'darwin':
                layer2addrfam = socket.AddressFamily.AF_LINK
            elif sys.platform == 'linux':
                layer2addrfam = socket.AddressFamily.AF_PACKET
            else:
                raise RuntimeException("Platform not supported")

            macaddr = "00:00:00:00:00:00"
            ipaddr = mask = "0.0.0.0"
            for addrinfo in ifaddrs:
                if addrinfo.family == socket.AddressFamily.AF_INET:
                    ipaddr = IPv4Address(addrinfo.address)
                    mask = IPv4Address(addrinfo.netmask)
                elif addrinfo.family == layer2addrfam:
                    macaddr = EthAddr(addrinfo.address)

            ifnum = socket.if_nametoindex(devname)
            devinfo[devname] = Interface(devname, macaddr, ipaddr, netmask=mask, ifnum=ifnum, iftype=devtype[devname])
        return devinfo
585918
private List<InetAddress> findAddresses() throws HarvestException {
		// Stores found addresses
		List<InetAddress> found = new ArrayList<InetAddress>(3);

		// Retrieve list of available network interfaces
		Enumeration<NetworkInterface> interfaces = getNetworkInterfaces();
		while (interfaces.hasMoreElements()) {
			NetworkInterface iface = interfaces.nextElement();

			// Evaluate network interface
			if (!useNetworkInterface(iface)) {
				continue;
			}

			// Retrieve list of available addresses from the network interface
			Enumeration<InetAddress> addresses = iface.getInetAddresses();

			while (addresses.hasMoreElements()) {
				InetAddress address = addresses.nextElement();

				// loopback addresses are discarded
				if (address.isLoopbackAddress()) {
					continue;
				}

				// Ignore IPv6 addresses for now
				if (address instanceof Inet4Address) {
					found.add(address);
				}
			}
		}
		return found;
	}
42877
def get_lldp_neighbors(self):
        """"""
        lldp = {}
        neighbors_detail = self.get_lldp_neighbors_detail()
        for intf_name, entries in neighbors_detail.items():
            lldp[intf_name] = []
            for lldp_entry in entries:
                hostname = lldp_entry["remote_system_name"]
                # Match IOS behaviour of taking remote chassis ID
                # When lacking a system name (in show lldp neighbors)
                if hostname == "N/A":
                    hostname = lldp_entry["remote_chassis_id"]
                lldp_dict = {"port": lldp_entry["remote_port"], "hostname": hostname}
                lldp[intf_name].append(lldp_dict)

        return lldp
843648
def _list_interface_private_addrs(eni_desc):
    '''
    
    '''
    primary = eni_desc.get('privateIpAddress')
    if not primary:
        return None

    addresses = [primary]

    lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
    if not isinstance(lst, list):
        return addresses

    for entry in lst:
        if entry.get('primary') == 'true':
            continue
        if entry.get('privateIpAddress'):
            addresses.append(entry.get('privateIpAddress'))

    return addresses
1208151
def in6_getifaddr():
    
    ifaddrs = []
    ip6s = get_ips(v6=True)
    for iface in ip6s:
        ips = ip6s[iface]
        for ip in ips:
            scope = in6_getscope(ip)
            ifaddrs.append((ip, scope, iface))
    # Appends Npcap loopback if available
    if conf.use_npcap and scapy.consts.LOOPBACK_INTERFACE:
        ifaddrs.append(("::1", 0, scapy.consts.LOOPBACK_INTERFACE))
    return ifaddrs
855842
def get_interface_addresses():
    

    addresses = []
    ifaces = netifaces.interfaces()
    for iface in ifaces:
        addrs = netifaces.ifaddresses(iface)
        families = addrs.keys()

        # put IPv4 to the end so it lists as the main iface address
        if netifaces.AF_INET in families:
            families.remove(netifaces.AF_INET)
            families.append(netifaces.AF_INET)

        for family in families:
            for addr in addrs[family]:
                address = {
                    'name': iface,
                    'family': family,
                    'ip': addr['addr'],
                }
                addresses.append(address)

    return addresses
1359614
def _get_ids_from_hostname(self, hostname):
        """"""
        results = self.list_hardware(hostname=hostname, mask="id")
        return [result['id'] for result in results]
526659
def get_if_raw_addr(ifname):
    """"""  # noqa: E501

    # Get ifconfig output
    try:
        fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        warning("Failed to execute ifconfig: (%s)", msg)
        return b"\0\0\0\0"

    # Get IPv4 addresses
    addresses = [l for l in fd if l.find("inet ") >= 0]
    if not addresses:
        warning("No IPv4 address found on %s !", ifname)
        return b"\0\0\0\0"

    # Pack the first address
    address = addresses[0].split(' ')[1]
    if '/' in address:  # NetBSD 8.0
        address = address.split("/")[0]
    return socket.inet_pton(socket.AF_INET, address)
800156
def GetMacAddresses(self):
    """"""
    result = set()
    for interface in self.interfaces:
      if (interface.mac_address and
          interface.mac_address != b"\x00" * len(interface.mac_address)):
        result.add(Text(interface.mac_address.human_readable_address))
    return sorted(result)
88261
def wd_addr(self):
        
        address = windivert_dll.WinDivertAddress()
        address.IfIdx, address.SubIfIdx = self.interface
        address.Direction = self.direction
        return address
676403
def GetIPAddresses(self):
    """"""
    results = []
    for address in self.addresses:
      human_readable_address = address.human_readable_address
      if human_readable_address is not None:
        results.append(human_readable_address)

    return results
115439
def interfaces():
    

    results = []
    if not sys.platform.startswith("win"):
        net_if_addrs = psutil.net_if_addrs()
        for interface in sorted(net_if_addrs.keys()):
            ip_address = ""
            mac_address = ""
            netmask = ""
            interface_type = "ethernet"
            for addr in net_if_addrs[interface]:
                # get the first available IPv4 address only
                if addr.family == socket.AF_INET:
                    ip_address = addr.address
                    netmask = addr.netmask
                if addr.family == psutil.AF_LINK:
                    mac_address = addr.address
            if interface.startswith("tap"):
                # found no way to reliably detect a TAP interface
                interface_type = "tap"
            results.append({"id": interface,
                            "name": interface,
                            "ip_address": ip_address,
                            "netmask": netmask,
                            "mac_address": mac_address,
                            "type": interface_type})
    else:
        try:
            service_installed = True
            if not _check_windows_service("npf") and not _check_windows_service("npcap"):
                service_installed = False
            else:
                results = get_windows_interfaces()
        except ImportError:
            message = "pywin32 module is not installed, please install it on the server to get the available interface names"
            raise aiohttp.web.HTTPInternalServerError(text=message)
        except Exception as e:
            log.error("uncaught exception {type}".format(type=type(e)), exc_info=1)
            raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e))

        if service_installed is False:
            raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running")

    # This interface have special behavior
    for result in results:
        result["special"] = False
        for special_interface in ("lo", "vmnet", "vboxnet", "docker", "lxcbr",
                                  "virbr", "ovs-system", "veth", "fw", "p2p",
                                  "bridge", "vmware", "virtualbox", "gns3"):
            if result["name"].lower().startswith(special_interface):
                result["special"] = True
        for special_interface in ("-nic"):
            if result["name"].lower().endswith(special_interface):
                result["special"] = True
    return results
276921
def hostapi_info(index=None):
    
    if index is None:
        return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount()))
    else:
        info = _pa.Pa_GetHostApiInfo(index)
        if not info:
            raise RuntimeError("Invalid host API")
        assert info.structVersion == 1
        return {'name': ffi.string(info.name).decode(errors='ignore'),
                'default_input_device': info.defaultInputDevice,
                'default_output_device': info.defaultOutputDevice}
111187
def _interfaces_ipconfig(out):
    '''
    
    '''
    ifaces = dict()
    iface = None
    adapter_iface_regex = re.compile(r'adapter (\S.+):$')

    for line in out.splitlines():
        if not line:
            continue
        # TODO what does Windows call Infiniband and 10/40gige adapters
        if line.startswith('Ethernet'):
            iface = ifaces[adapter_iface_regex.search(line).group(1)]
            iface['up'] = True
            addr = None
            continue
        if iface:
            key, val = line.split(',', 1)
            key = key.strip(' .')
            val = val.strip()
            if addr and key == 'Subnet Mask':
                addr['netmask'] = val
            elif key in ('IP Address', 'IPv4 Address'):
                if 'inet' not in iface:
                    iface['inet'] = list()
                addr = {'address': val.rstrip('(Preferred)'),
                        'netmask': None,
                        'broadcast': None}  # TODO find the broadcast
                iface['inet'].append(addr)
            elif 'IPv6 Address' in key:
                if 'inet6' not in iface:
                    iface['inet'] = list()
                # XXX What is the prefixlen!?
                addr = {'address': val.rstrip('(Preferred)'),
                        'prefixlen': None}
                iface['inet6'].append(addr)
            elif key == 'Physical Address':
                iface['hwaddr'] = val
            elif key == 'Media State':
                # XXX seen used for tunnel adaptors
                # might be useful
                iface['up'] = (val != 'Media disconnected')
516391
function findWindowsPortRange() {
  var deferredRange = promise.defer();
  // First, check if we're running on XP.  If this initial command fails,
  // we just fallback on the default IANA range.
  return execute('cmd.exe /c ver').then(function(stdout) {
    if (/Windows XP/.test(stdout)) {
      // TODO: Try to read these values from the registry.
      return {min: 1025, max: 5000};
    } else {
      return execute('netsh int ipv4 show dynamicport tcp').
          then(function(stdout) {
            /* > netsh int ipv4 show dynamicport tcp
              Protocol tcp Dynamic Port Range
              ---------------------------------
              Start Port : 49152
              Number of Ports : 16384
             */
            var range = stdout.split(/\n/).filter(function(line) {
              return /.*:\s*\d+/.test(line);
            }).map(function(line) {
              return Number(line.split(/:\s*/)[1]);
            });

            return {
              min: range[0],
              max: range[0] + range[1]
            };
          });
    }
  });
}