find usage of network interfaces
515426
def _find_usage_network_interfaces(self):
        """"""
        enis = paginate_dict(
            self.conn.describe_network_interfaces,
            alc_marker_path=['NextToken'],
            alc_data_path=['NetworkInterfaces'],
            alc_marker_param='NextToken'
        )

        self.limits['Network interfaces per Region']._add_current_usage(
            len(enis['NetworkInterfaces']),
            aws_type='AWS::EC2::NetworkInterface'
        )
599073
def get_my_ips():
    """"""
    ips = list()
    if not os.path.exists("/sys/class/net"): # not linux
        return ['127.0.0.1']
    for ifdev in os.listdir("/sys/class/net"):
        if ifdev == "lo":
            continue
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ips.append(socket.inet_ntoa(fcntl.ioctl(
                sock.fileno(),
                0x8915,  # SIOCGIFADDR
                struct.pack('256s', ifdev[:15].encode())
            )[20:24]))
        except OSError:
            pass
    return ips
324351
def get_interfaces(self):
        """"""
        result = {}

        interfaces = junos_views.junos_iface_table(self.device)
        interfaces.get()

        # convert all the tuples to our pre-defined dict structure
        for iface in interfaces.keys():
            result[iface] = {
                'is_up': interfaces[iface]['is_up'],
                'is_enabled': interfaces[iface]['is_enabled'],
                'description': (interfaces[iface]['description'] or u''),
                'last_flapped': float((interfaces[iface]['last_flapped'] or -1)),
                'mac_address': napalm_base.helpers.convert(
                    napalm_base.helpers.mac,
                    interfaces[iface]['mac_address'],
                    py23_compat.text_type(interfaces[iface]['mac_address'])),
                'speed': -1
            }
            # result[iface]['last_flapped'] = float(result[iface]['last_flapped'])

            match = re.search(r'(\d+)(\w*)', interfaces[iface]['speed'] or u'')
            if match is None:
                continue
            speed_value = napalm_base.helpers.convert(int, match.group(1), -1)
            if speed_value == -1:
                continue
            speed_unit = match.group(2)
            if speed_unit.lower() == 'gbps':
                speed_value *= 1000
            result[iface]['speed'] = speed_value

        return result
189319
def GetEnabledInterfaces():
  
  interfaces = []
  show_args = ['/c', 'netsh', 'show', 'interface']
  # pylint: disable=undefined-variable
  res = client_utils_common.Execute(
      'cmd', show_args, time_limit=-1, bypass_whitelist=True)
  pattern = re.compile(r'\s*')
  for line in res[0].split('\r\n'):  # res[0] is stdout.
    interface_info = pattern.split(line)
    if 'Enabled' in interface_info:
      interfaces.extend(interface_info[-1:])
  return interfaces
1234761
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))

  addresses = {}
  macs = {}
  ifs = set()

  m = p_ifa
  while m:
    ifname = ctypes.string_at(m.contents.ifa_name)
    ifs.add(ifname)
    try:
      iffamily = ord(m.contents.ifa_addr[0])

      if iffamily == 0x2:  # AF_INET
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrin))
        ip4 = bytes(list(data.contents.sin_addr))
        address_type = rdf_client_network.NetworkAddress.Family.INET
        address = rdf_client_network.NetworkAddress(
            address_type=address_type, packed_bytes=ip4)
        addresses.setdefault(ifname, []).append(address)

      if iffamily == 0x11:  # AF_PACKET
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrll))
        addlen = data.contents.sll_halen
        macs[ifname] = bytes(list(data.contents.sll_addr[:addlen]))

      if iffamily == 0xA:  # AF_INET6
        data = ctypes.cast(m.contents.ifa_addr, ctypes.POINTER(Sockaddrin6))
        ip6 = bytes(list(data.contents.sin6_addr))
        address_type = rdf_client_network.NetworkAddress.Family.INET6
        address = rdf_client_network.NetworkAddress(
            address_type=address_type, packed_bytes=ip6)
        addresses.setdefault(ifname, []).append(address)
    except ValueError:
      # Some interfaces don't have a iffamily and will raise a null pointer
      # exception. We still want to send back the name.
      pass

    m = m.contents.ifa_next

  libc.freeifaddrs(p_ifa)

  for interface in ifs:
    mac = macs.setdefault(interface, b"")
    address_list = addresses.setdefault(interface, b"")
    args = {"ifname": interface}
    if mac:
      args["mac_address"] = mac
    if addresses:
      args["addresses"] = address_list
    yield rdf_client_network.Interface(**args)
426612
function getNetworkInterfaces() {
    const ret = {};
    for (const macinfo of Object.values(macs)) {
        if (!macinfo.self) {
            continue;
        }
        ret[macinfo.net] = objCpy(macinfo);
    }
    return ret;
}
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')
1046356
def network_io_counters(interface=None):
    '''
    
    '''
    if not interface:
        return dict(psutil.net_io_counters()._asdict())
    else:
        stats = psutil.net_io_counters(pernic=True)
        if interface in stats:
            return dict(stats[interface]._asdict())
        else:
            return False
976982
def get_using_network_time():
    '''
    
    '''
    ret = salt.utils.mac_utils.execute_return_result(
        'systemsetup -getusingnetworktime')

    return salt.utils.mac_utils.validate_enabled(
        salt.utils.mac_utils.parse_return(ret)) == 'on'
1179968
def _get_network(self):
        '''
        
        '''
        data = dict()
        data['interfaces'] = salt.utils.network.interfaces()
        data['subnets'] = salt.utils.network.subnets()

        return data
1054830
def find_usage(self):
        
        logger.debug("Checking usage for service %s", self.service_name)
        for lim in self.limits.values():
            lim._reset_usage()
        try:
            self.connect()
            resp = self.conn.get_send_quota()
        except EndpointConnectionError as ex:
            logger.warning('Skipping SES: %s', str(ex))
            return
        except ClientError as ex:
            if ex.response['Error']['Code'] in ['AccessDenied', '503']:
                logger.warning('Skipping SES: %s', ex)
                return
            raise
        self.limits['Daily sending quota']._add_current_usage(
            resp['SentLast24Hours']
        )
        self._have_usage = True
        logger.debug("Done checking usage.")
940452
def _get_tcpip_interface_info(interface):
    '''
    
    '''
    base_information = _get_base_interface_info(interface)
    if base_information['ipv4']['requestmode'] == 'static':
        settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address'])
        base_information['ipv4']['address'] = settings['IP_Address']
        base_information['ipv4']['netmask'] = settings['Subnet_Mask']
        base_information['ipv4']['gateway'] = settings['Gateway']
        base_information['ipv4']['dns'] = [settings['DNS_Address']]
    elif base_information['up']:
        base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr)
        base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask)
        base_information['ipv4']['gateway'] = '0.0.0.0'
        base_information['ipv4']['dns'] = _get_dns_info()
        with salt.utils.files.fopen('/proc/net/route', 'r') as route_file:
            pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name),
                                 re.MULTILINE)
            match = pattern.search(route_file.read())
            iface_gateway_hex = None if not match else match.group(1)
        if iface_gateway_hex is not None and len(iface_gateway_hex) == 8:
            base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16))
                                                            for i in range(6, -1, -2)])
    return base_information
410627
def collect_usage_pieces(self, ctx):
        """"""
        pieces = super(ProfilingCommand, self).collect_usage_pieces(ctx)
        assert pieces[-1] == '[ARGV]...'
        pieces.insert(-1, 'SCRIPT')
        pieces.insert(-1, '[--]')
        return pieces
477411
def network_info():
    

    def extract(host, family):
        return socket.getaddrinfo(host, None, family)[0][4][0]
    host = socket.gethostname()
    response = {
        'hostname': host,
        'ipv4': None,
        'ipv6': None
    }
    with suppress(IndexError, socket.gaierror):
        response['ipv4'] = extract(host, socket.AF_INET)
    with suppress(IndexError, socket.gaierror):
        response['ipv6'] = extract(host, socket.AF_INET6)
    return response
309534
def _find_usage_subnets(self):
        """"""
        # subnets per VPC
        subnet_to_az = {}
        subnets = defaultdict(int)
        for subnet in self.conn.describe_subnets()['Subnets']:
            subnets[subnet['VpcId']] += 1
            subnet_to_az[subnet['SubnetId']] = subnet['AvailabilityZone']
        for vpc_id in subnets:
            self.limits['Subnets per VPC']._add_current_usage(
                subnets[vpc_id],
                aws_type='AWS::EC2::VPC',
                resource_id=vpc_id
            )
        return subnet_to_az
103241
def usage(self):
        
        arg_list = ' '.join(self.cmd_args).upper()
        name = self.interface.name()
        return '%s [options] %s %s' % (name, self.__name__, arg_list)
876794
def check_for_eni_source():
    '''  '''

    with open('/etc/network/interfaces', 'r') as eni:
        for line in eni:
            if line == 'source /etc/network/interfaces.d/*':
                return
    with open('/etc/network/interfaces', 'a') as eni:
        eni.write('\nsource /etc/network/interfaces.d/*')