Parses contents of the intrusive linked list of `ifaddrs`.

  Args:
    ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.

  Returns:
    An iterator over instances of `rdf_client_network.Interface`.
2908
def ParseIfaddrs(ifaddrs):
  
  precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs))

  ifaces = {}

  for ifaddr in IterIfaddrs(ifaddrs):
    ifname = ctypes.string_at(ifaddr.ifa_name).decode("utf-8")
    iface = ifaces.setdefault(ifname, rdf_client_network.Interface())
    iface.ifname = ifname

    if not ifaddr.ifa_addr:
      continue

    sockaddr = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddr))
    iffamily = sockaddr.contents.sa_family
    if iffamily == AF_INET:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET
      address.packed_bytes = struct.pack("=L", sockaddrin.contents.sin_addr)
      iface.addresses.append(address)
    elif iffamily == AF_INET6:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin6))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET6
      address.packed_bytes = bytes(list(sockaddrin.contents.sin6_addr))
      iface.addresses.append(address)
    elif iffamily == AF_LINK:
      sockaddrdl = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrdl))

      nlen = sockaddrdl.contents.sdl_nlen
      alen = sockaddrdl.contents.sdl_alen
      iface.mac_address = bytes(sockaddrdl.contents.sdl_data[nlen:nlen + alen])
    else:
      raise ValueError("Unexpected socket address family: %s" % iffamily)

  return itervalues(ifaces)
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
425376
def ParseForwardedIps(self, forwarded_ips):
    
    addresses = []
    forwarded_ips = forwarded_ips or []
    for ip in forwarded_ips:
      if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)):
        addresses.append(ip[:-3] if ip.endswith('/32') else ip)
      else:
        self.logger.warning('Could not parse IP address: "%s".', ip)
    return addresses
1023773
public static <T> List<T> list(boolean isLinked, Iterator<T> iter) {
		final List<T> list = list(isLinked);
		if (null != iter) {
			while (iter.hasNext()) {
				list.add(iter.next());
			}
		}
		return list;
	}
1045552
def update(cls):
        
        ifaddrs = getifaddrs()
        # Create new interfaces
        for ifname in ifaddrs.keys():
            if filter(ifname.startswith, cls.NAME_FILTER):
                cls.objects.get_or_create(name=ifname)

        # Delete no longer existing ones
        cls.objects.exclude(name__in=ifaddrs.keys()).delete()
1002138
def load(self, addr, length=1):
        
        if addr is None:
            return
        elif not isinstance(addr, Iterable):
            self.first_level.load(addr, length=length)
        else:
            self.first_level.iterload(addr, length=length)
1005119
def ipfix():
    
    if not hasattr(ipfix, 'ipflist'):
        ilist = []
        try:
            data = requests.get('http://www.iana.org/assignments/ipfix/ipfix-'
                                'information-elements.csv')
        except requests.exceptions.RequestException:
            return []

        for line in data.iter_lines():
            if line:
                line = line.decode("utf-8")
                if re.match(r'^\d+(,[a-zA-Z0-9]+){2},', line):
                    vals = line.split(',')
                    if vals[1]:
                        ilist.append(vals[1])

        ipfix.ipflist = ilist
    return ipfix.ipflist
374585
def parse_links(args_link):
    
    links = []
    if (args_link is not None):
        for link_str in args_link:
            try:
                links.append(parse_link(link_str))
            except ClientFatalError as e:
                raise ClientFatalError(
                    "Bad --link option '%s' (%s)" %
                    (link_str, str(e)))
    return(links)
1362935
def _get_ipv6addrs(self):
        
        addrs = self._get_addrs()
        ipv6addrs = addrs.get(netifaces.AF_INET6)
        if not ipv6addrs:
            return {}
        return ipv6addrs[0]
448959
def interfaces_info():
    
    def replace(value):
        if value == netifaces.AF_LINK:
            return 'link'
        if value == netifaces.AF_INET:
            return 'ipv4'
        if value == netifaces.AF_INET6:
            return 'ipv6'
        return value

    results = {}
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        results[iface] = {replace(k): v for k, v in addrs.items()}

    return results
1107178
def parse_addresses(addresses)
      return if addresses.empty?
      uris = addresses.is_a?(Array) ? addresses.dup : addresses.split(/[\s,]+/)
      uris.map! do |uri_string|
        begin
          uri = URI.parse(uri_string)
        rescue URI::InvalidURIError
          # IP based hosts without a scheme will fail to parse
        end
        if uri && uri.scheme && uri.host
          raise(InvalidURIScheme, "Invalid beanstalk URI: #{uri_string}") unless uri.scheme == 'beanstalk'
          host = uri.host
          port = uri.port
        else
          # if parse failure or missing scheme or host, assume the uri format is a
          # hostname optionally followed by a port.
          # i.e. 'localhost:11300' or '0.0.0.0'
          match = uri_string.split(/:/)
          host = match[0]
          port = match[1]
        end
        "#{host}:#{port || 11300}"
      end
    end
659468
public static Map<String, Set<InetAddress>> getNetworkInterfaceAddresses(boolean includeLoopback) {
        //JVM returns interfaces in a non-predictable order, so to make this more predictable
        //let's have them sort by interface name (by using a TreeMap).
        Map<String, Set<InetAddress>> interfaceAddressMap = new TreeMap<>();
        try {
            Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
            while (ifaces.hasMoreElements()) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                //We only care about usable interfaces.
                if (!iface.isUp()) {
                    continue;
                }
                if (!includeLoopback && iface.isLoopback()) {
                    continue;
                }
                String name = iface.getName();
                Enumeration<InetAddress> ifaceAdresses = iface.getInetAddresses();
                while (ifaceAdresses.hasMoreElements()) {
                    InetAddress ia = ifaceAdresses.nextElement();
                    if (!includeLoopback && ia.isLoopbackAddress()) {
                        continue;
                    }
                    // We want to filter out mac addresses
                    // Let's filter out docker interfaces too
                    if (!ia.getHostAddress().contains(":") && !(name != null && name.toLowerCase().contains("docker"))) {
                        Set<InetAddress> addresses = interfaceAddressMap.get(name);
                        if (addresses == null) {
                            addresses = new LinkedHashSet<>();
                        }
                        addresses.add(ia);
                        interfaceAddressMap.put(name, addresses);
                    }
                }
            }
        } catch (SocketException ex) {
            //noop
        }
        return interfaceAddressMap;
    }
813580
def get_iface_from_addr(addr):
    """"""
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        for inet_type in addresses:
            for _addr in addresses[inet_type]:
                _addr = _addr['addr']
                # link local
                ll_key = re.compile("(.+)%.*")
                raw = re.match(ll_key, _addr)
                if raw:
                    _addr = raw.group(1)

                if _addr == addr:
                    log("Address '%s' is configured on iface '%s'" %
                        (addr, iface))
                    return iface

    msg = "Unable to infer net iface on which '%s' is configured" % (addr)
    raise Exception(msg)
336527
def in6_getifaddr():
    

    # List all network interfaces
    if OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else:  # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    return ret
739656
def EnumerateInterfacesFromClient(args):
  """"""
  del args  # Unused

  libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
  ifa = Ifaddrs()
  p_ifa = ctypes.pointer(ifa)
  libc.getifaddrs(ctypes.pointer(p_ifa))

  for iface in ParseIfaddrs(p_ifa):
    yield iface

  libc.freeifaddrs(p_ifa)
973433
def _parse_graph(self):

		'''
		
		'''

		# if resource exists, parse self.rdf.data
		if self.exists:
			self.rdf.graph = self.repo.api.parse_rdf_payload(self.rdf.data, self.headers)

		# else, create empty graph
		else:
			self.rdf.graph = rdflib.Graph()

		# bind any additional namespaces from repo instance, but do not override
		self.rdf.namespace_manager = rdflib.namespace.NamespaceManager(self.rdf.graph)
		for ns_prefix, ns_uri in self.rdf.prefixes.__dict__.items():
			self.rdf.namespace_manager.bind(ns_prefix, ns_uri, override=False)

		# conversely, add namespaces from parsed graph to self.rdf.prefixes
		for ns_prefix, ns_uri in self.rdf.graph.namespaces():
			setattr(self.rdf.prefixes, ns_prefix, rdflib.Namespace(ns_uri))
			setattr(self.rdf.uris, rdflib.Namespace(ns_uri), ns_prefix)

		# pin old graph to resource, create copy graph for modifications
		self.rdf._orig_graph = copy.deepcopy(self.rdf.graph)

		# parse triples for object-like access
		self.parse_object_like_triples()
461416
def parse_addr(addr, *, proto=None, host=None):
    
    port = None

    if isinstance(addr, Address):
        return addr
    elif isinstance(addr, str):
        if addr.startswith('http://'):
            proto, addr = 'http', addr[7:]
        if addr.startswith('udp://'):
            proto, addr = 'udp', addr[6:]
        elif addr.startswith('tcp://'):
            proto, addr = 'tcp', addr[6:]
        elif addr.startswith('unix://'):
            proto, addr = 'unix', addr[7:]
        a, _, b = addr.partition(':')
        host = a or host
        port = b or port
    elif isinstance(addr, (tuple, list)):
        # list is not good
        a, b = addr
        host = a or host
        port = b or port
    elif isinstance(addr, int):
        port = addr
    else:
        raise ValueError('bad value')

    if port is not None:
        port = int(port)
    return Address(proto, host, port)