Python netifaces 模块,AF_INET 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用netifaces.AF_INET

项目:Static-UPnP    作者:nigelb    | 项目源码 | 文件源码
def setup_sockets(self):

    self.sockets = {}
    ip_addresses = get_interface_addresses(self.logger)

    self.ip_addresses = ip_addresses

    multi_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    multi_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl)

    for ip in ip_addresses:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mreq=socket.inet_aton(self.address)+socket.inet_aton(ip)
        multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.logger.info("Regestering multicast for: %s: %s"%(self.address, ip))
        sock.bind((ip, self.port))

        self.sockets[ip] = sock

    multi_sock.bind(("", self.port))
    self.socks = [self.sockets[x] for x in self.sockets.keys()]
    self.multi_sock = multi_sock
项目:supvisors    作者:julien6387    | 项目源码 | 文件源码
def ipv4():
        """ Get all IPv4 addresses for all interfaces. """
        try:
            from netifaces import interfaces, ifaddresses, AF_INET
            # to not take into account loopback addresses (no interest here)
            addresses = []
            for interface in interfaces():
                config = ifaddresses(interface)
                # AF_INET is not always present
                if AF_INET in config.keys():
                    for link in config[AF_INET]:
                        # loopback holds a 'peer' instead of a 'broadcast' address
                        if 'addr' in link.keys() and 'peer' not in link.keys():
                            addresses.append(link['addr']) 
            return addresses
        except ImportError:
            return []
项目:pscheduler    作者:perfsonar    | 项目源码 | 文件源码
def __init__(self,
                 data   # Data suitable for this class
                 ):

        valid, message = data_is_valid(data)
        if not valid:
            raise ValueError("Invalid data: %s" % message)

        self.cidrs = []
        for iface in netifaces.interfaces():
            ifaddrs = netifaces.ifaddresses(iface)
            if netifaces.AF_INET in ifaddrs:
                for ifaddr in ifaddrs[netifaces.AF_INET]:
                    if 'addr' in ifaddr:
                        self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr']))
            if netifaces.AF_INET6 in ifaddrs:
                for ifaddr in ifaddrs[netifaces.AF_INET6]:
                    if 'addr' in ifaddr:
                        #add v6 but remove stuff like %eth0 that gets thrown on end of some addrs
                        self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'].split('%')[0]))
项目:pykit    作者:baishancloud    | 项目源码 | 文件源码
def get_host_devices(iface_prefix=''):

    rst = {}

    for ifacename in netifaces.interfaces():

        if not ifacename.startswith(iface_prefix):
            continue

        addrs = netifaces.ifaddresses(ifacename)

        if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs:

            ips = [addr['addr'] for addr in addrs[netifaces.AF_INET]]

            for ip in ips:
                if is_ip4_loopback(ip):
                    break
            else:
                rst[ifacename] = {'INET': addrs[netifaces.AF_INET],
                                  'LINK': addrs[netifaces.AF_LINK]}

    return rst
项目:Static-UPnP    作者:nigelb    | 项目源码 | 文件源码
def get_interface_addresses(logger):
    import StaticUPnP_Settings
    interface_config = Namespace(**StaticUPnP_Settings.interfaces)
    ip_addresses = StaticUPnP_Settings.ip_addresses
    if len(ip_addresses) == 0:
        import netifaces
        ifs = netifaces.interfaces()
        if len(interface_config.include) > 0:
            ifs = interface_config.include
        if len(interface_config.exclude) > 0:
            for iface in interface_config.exclude:
                ifs.remove(iface)

        for i in ifs:
            addrs = netifaces.ifaddresses(i)
            if netifaces.AF_INET in addrs:
                for addr in addrs[netifaces.AF_INET]:
                    ip_addresses.append(addr['addr'])
                    logger.info("Regestering multicast on %s: %s"%(i, addr['addr']))
    return ip_addresses
项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
def internal_ip(pl, interface='auto', ipv=4):
        family = netifaces.AF_INET6 if ipv == 6 else netifaces.AF_INET
        if interface == 'auto':
            try:
                interface = next(iter(sorted(netifaces.interfaces(), key=_interface_key, reverse=True)))
            except StopIteration:
                pl.info('No network interfaces found')
                return None
        elif interface == 'default_gateway':
            try:
                interface = netifaces.gateways()['default'][family][1]
            except KeyError:
                pl.info('No default gateway found for IPv{0}', ipv)
                return None
        addrs = netifaces.ifaddresses(interface)
        try:
            return addrs[family][0]['addr']
        except (KeyError, IndexError):
            pl.info("No IPv{0} address found for interface {1}", ipv, interface)
            return None
项目:packet-queue    作者:google    | 项目源码 | 文件源码
def configure(protocol, port, pipes, interface):
  remove_all()
  reactor.addSystemEventTrigger('after', 'shutdown', remove_all)

  # gets default (outward-facing) network interface (e.g. deciding which of
  # eth0, eth1, wlan0 is being used by the system to connect to the internet)
  if interface == "auto":
    interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
  else:
    if interface not in netifaces.interfaces():
      raise ValueError("Given interface does not exist.", interface)

  add(protocol, port, interface)
  manager = libnetfilter_queue.Manager()

  manager.bind(UP_QUEUE, packet_handler(manager, pipes.up))
  manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down))

  reader = abstract.FileDescriptor()
  reader.doRead = manager.process
  reader.fileno = lambda: manager.fileno
  reactor.addReader(reader)
项目:deb-oslo.utils    作者:openstack    | 项目源码 | 文件源码
def get_my_ipv4():
    """Returns the actual ipv4 of the local machine.

    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, IP from RFC5737 is used, but the specific address does not
    matter much. No traffic is actually sent.

    .. versionadded:: 1.1

    .. versionchanged:: 1.2.1
       Return ``'127.0.0.1'`` if there is no default interface.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('192.0.2.0', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return _get_my_ipv4_address()
项目:deb-oslo.utils    作者:openstack    | 项目源码 | 文件源码
def _get_my_ipv4_address():
    """Figure out the best ipv4
    """
    LOCALHOST = '127.0.0.1'
    gtw = netifaces.gateways()
    try:
        interface = gtw['default'][netifaces.AF_INET][1]
    except (KeyError, IndexError):
        LOG.info(_LI('Could not determine default network interface, '
                     'using 127.0.0.1 for IPv4 address'))
        return LOCALHOST

    try:
        return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
    except (KeyError, IndexError):
        LOG.info(_LI('Could not determine IPv4 address for interface %s, '
                     'using 127.0.0.1'),
                 interface)
    except Exception as e:
        LOG.info(_LI('Could not determine IPv4 address for '
                     'interface %(interface)s: %(error)s'),
                 {'interface': interface, 'error': e})
    return LOCALHOST
项目:fuel-ccp-entrypoint    作者:openstack    | 项目源码 | 文件源码
def get_ip_address(iface):
    """Get IP address of the interface connected to the network.

    If there is no such an interface, then localhost is returned.
    """

    if iface not in netifaces.interfaces():
        LOG.warning("Can't find interface '%s' in the host list of interfaces",
                    iface)
        return '127.0.0.1'

    address_family = netifaces.AF_INET

    if address_family not in netifaces.ifaddresses(iface):
        LOG.warning("Interface '%s' doesnt configured with ipv4 address",
                    iface)
        return '127.0.0.1'

    for ifaddress in netifaces.ifaddresses(iface)[address_family]:
        if 'addr' in ifaddress:
            return ifaddress['addr']
        else:
            LOG.warning("Can't find ip addr for interface '%s'", iface)
            return '127.0.0.1'
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def get_if_raw_addr(iff):
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = b"\0\0\0\0"
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      while p:
        if p.contents.name.endswith(iff.encode('ascii')):
          a = p.contents.addresses
          while a:
            if a.contents.addr.contents.sa_family == socket.AF_INET:
              ap = a.contents.addr
              val = cast(ap, POINTER(sockaddr_in))
              ret = bytes(val.contents.sin_addr[:4])
            a = a.contents.next
          break
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self):
        self.tcpPort = 31337
        self.tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcpsocket.bind(("0.0.0.0", self.tcpPort))
        self.tcpsocket.listen(10)

        self.discoverysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

        self.glfwWorkers = {}

        self.controllerConn = None
        self.controllerAddr = None
        self.outbuf = ""    # IO buffer for controller
        self.inbuf = ""

        self.monitors = glfw.get_monitors()

        for monitor in glfw.get_monitors():
            self.glfwWorkers[bytes.decode(glfw.get_monitor_name(monitor))] = glfwWorker(monitor)
项目:tools    作者:apertoso    | 项目源码 | 文件源码
def get_lo_alias_addr():
    # check all interfaces an try to find one with address 127.0.0.1
    # If that interface has another address, that's the one we need.
    ifname_loopback = None
    for interface in netifaces.interfaces():
        ip_addresses = []
        interface_addresses = netifaces.ifaddresses(interface)
        if netifaces.AF_INET not in interface_addresses:
            continue
        for address_data in interface_addresses[netifaces.AF_INET]:
            if address_data.get('addr') == '127.0.0.1':
                ifname_loopback = interface
            elif address_data.get('addr'):
                ip_addresses.append(address_data.get('addr'))
        if interface == ifname_loopback and ip_addresses:
            return ip_addresses[0]
项目:pyimc    作者:oysstu    | 项目源码 | 文件源码
def get_interfaces(ignore_local=True):
    """
    Retrieves the address of all external interfaces (lo 127.0.0.1 ignored)
    :return: List of tuples (interface, addr)
    """
    interfaces = netifaces.interfaces()
    if_ext = []
    for i in interfaces:
        if i == 'lo' and ignore_local:
            continue
        iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
        if iface:
            for j in iface:
                if_ext.append((i, j['addr'], j['netmask']))

    return if_ext
项目:caproto    作者:NSLS-II    | 项目源码 | 文件源码
def get_broadcast_addr_list():
    import netifaces

    interfaces = [netifaces.ifaddresses(interface)
                  for interface in netifaces.interfaces()
                  ]
    bcast = [af_inet_info['broadcast']
             if 'broadcast' in af_inet_info
             else af_inet_info['peer']

             for interface in interfaces
             if netifaces.AF_INET in interface
             for af_inet_info in interface[netifaces.AF_INET]
             ]

    print('Broadcast address list:', bcast)
    return ' '.join(bcast)
项目:caproto    作者:NSLS-II    | 项目源码 | 文件源码
def get_netifaces_addresses():
    '''Get a list of addresses + broadcast using netifaces

    Yields (address, broadcast_address)
    '''
    if netifaces is None:
        raise RuntimeError('netifaces unavailable')

    for iface in netifaces.interfaces():
        interface = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in interface:
            for af_inet_info in interface[netifaces.AF_INET]:
                addr = af_inet_info.get('addr', None)
                peer = af_inet_info.get('peer', None)
                broadcast = af_inet_info.get('broadcast', None)

                if addr is not None and broadcast is not None:
                    yield (addr, broadcast)
                elif peer is not None and broadcast is not None:
                    yield (peer, broadcast)
                elif addr is not None:
                    yield (addr, addr)
                elif peer is not None:
                    yield (peer, peer)
项目:caproto    作者:NSLS-II    | 项目源码 | 文件源码
def bcast_socket(socket_module=socket):
    """
    Make a socket and configure it for UDP broadcast.

    Parameters
    ----------
    socket_module: module, optional
        Default is the built-in :mod:`socket` module, but anything with the
        same interface may be used, such as :mod:`curio.socket`.
    """
    socket = socket_module
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    # for BSD/Darwin only
    try:
        socket.SO_REUSEPORT
    except AttributeError:
        ...
    else:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    return sock
项目:psystem    作者:gokhanm    | 项目源码 | 文件源码
def ip(self, interface_name):
        """
            interface: str, Interface Name
            return: List
                    [{'broadcast': '10.100.0.255', 'addr': '10.100.0.164', 'netmask': '255.255.255.0'}]
        """
        interface_check = self.interfaces

        if not interface_name in interface_check:
            raise WrongInterfaceName("Wrong Interface Name %s" % interface_name)

        addrs = netifaces.ifaddresses(interface_name)

        try:
            return addrs[netifaces.AF_INET]
        except KeyError:
            raise NotValidInterfaceName("Not valid interface name or may be
                                         virtual interface name %s" % interface_name)
项目:psystem    作者:gokhanm    | 项目源码 | 文件源码
def ip(self, interface_name, newip):
        """
            This function automatically will change netmask address.

            Checking interface first, if interface name found in Get().interfaces()
            validating Ipv4. After that applied ip address to interface

            interface_name: Applied Interface
            newip: New Ip Address

        """
        interface_check = Get().interfaces
        valid_ipv4 = validators.ipv4(newip)

        if not interface_name in interface_check:
            raise WrongInterfaceName("Wrong Interface Name %s" % interface_name)
        elif not valid_ipv4 is True:
            raise NotValidIPv4Address("Not Valid IPv4 Address %s" % newip)
        else:
            ifname = interface_name.encode(encoding='UTF-8')
            ipbytes = socket.inet_aton(newip)
            ifreq = struct.pack('16sH2s4s8s', ifname, AF_INET, b'\x00'*2, ipbytes, b'\x00'*8)
            fcntl.ioctl(self.sock, SIOCSIFADDR, ifreq)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def get_if_raw_addr(iff):
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = b"\0\0\0\0"
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      while p:
        if p.contents.name.endswith(iff.encode('ascii')):
          a = p.contents.addresses
          while a:
            if a.contents.addr.contents.sa_family == socket.AF_INET:
              ap = a.contents.addr
              val = cast(ap, POINTER(sockaddr_in))
              ret = bytes(val.contents.sin_addr[:4])
            a = a.contents.next
          break
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)
项目:dnsplit    作者:jrmdev    | 项目源码 | 文件源码
def proxyrequest(self, qname, request):
        reply = None

        ns = self.find_ns(qname)

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(3.0)
            sock.sendto(request, (ns, 53))
            reply = sock.recv(1024)
            sock.close()

        except Exception, e:
            print "[!] Could not proxy request %s to %s: %s" % (qname, ns, e)
        else:
            return reply

# UDP DNS Handler for incoming requests
项目:dnsplit    作者:jrmdev    | 项目源码 | 文件源码
def is_condition_met(rule):

    if rule['interface'] not in netifaces.interfaces():
        return False

    if rule['type'] == 'state':

        addr = netifaces.ifaddresses(rule['interface'])

        if rule['state'] == 'up' and netifaces.AF_INET in addr:
            return True

        if rule['state'] == 'down' and netifaces.AF_INET not in addr:
            return True

    elif rule['type'] == 'network':

        addresses = netifaces.ifaddresses(rule['interface'])
        for addr in addresses[netifaces.AF_INET]:
            if addr['addr'] in rule['network']:
                return True

    return False
项目:wireless-network-reproduction    作者:FinalTheory    | 项目源码 | 文件源码
def decide_iface(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("gmail.com", 80))
            local_ip = s.getsockname()[0]
            s.close()
        except:
            showwarning('Network Error',
                        ('Your host machine may not have a valid network connection.\n'
                         'You should **manually** choose your network device name in filter rule.'))
            return
        iface_lst = netifaces.interfaces()
        for iface in iface_lst:
            addrs = netifaces.ifaddresses(iface)
            if netifaces.AF_INET in addrs:
                addr_dict = addrs[netifaces.AF_INET][0]
                if 'addr' in addr_dict:
                    if addr_dict['addr'] == local_ip:
                        print 'Found activate network interface: %s' % iface
                        self.iface = iface
                        return
项目:raw-packet    作者:Vladimir-Ivanov-Git    | 项目源码 | 文件源码
def get_mac(iface, ip):
        gw_ip = ""
        gws = gateways()
        for gw in gws.keys():
            try:
                if str(gws[gw][AF_INET][1]) == iface:
                    gw_ip = str(gws[gw][AF_INET][0])
            except IndexError:
                if str(gws[gw][0][1]) == iface:
                    gw_ip = str(gws[gw][0][0])
        try:
            alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), iface=iface, timeout=10, verbose=0)
            return str(alive[0][1].hwsrc)
        except IndexError:
            try:
                alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=gw_ip), iface=iface, timeout=10, verbose=0)
                return str(alive[0][1].hwsrc)
            except:
                return "ff:ff:ff:ff:ff:ff"
        except:
            return "ff:ff:ff:ff:ff:ff"
项目:automatic-repo    作者:WZQ1397    | 项目源码 | 文件源码
def get_local_ip_address():
    import os
    import sys

    try:
        import netifaces
    except ImportError:
        try:
            command_to_execute = "pip install netifaces || easy_install netifaces"
            os.system(command_to_execute)
        except OSError:
            print "Can NOT install netifaces, Aborted!"
            sys.exit(1)
        import netifaces

    routingIPAddr = '127.0.0.1'

    for interface in netifaces.interfaces():
        if interface == netifaces.gateways()['default'][netifaces.AF_INET][1]:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                pass
    return routingIPAddr
项目:LinuxDrop    作者:Livin21    | 项目源码 | 文件源码
def get():
    print("Fetching list of available planets...")
    interface = get_interface_name()
    this_device_ip = ni.ifaddresses(interface)[ni.AF_INET][0]['addr']
    p2 = subprocess.Popen(["nmap", "-sP", this_device_ip + "/24"], stdout=subprocess.PIPE)
    res = p2.communicate()
    arr = ''.join(map(str, res)).replace("\n", " ").replace("(", "").replace(")", "").split(" ")
    ip_arr = []
    print("Locking on target beam...")
    for i in arr:
        print(".", end="")
        if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", i):
            ip_arr.append(i)

    correct_ips = find_correct_ips(ip_arr)
    return correct_ips
项目:python-arp-spoofer    作者:7BISSO    | 项目源码 | 文件源码
def do_inet(self, _AF):
        """Usage : inet [option], see 'man' for options"""

        if _AF == 'AF_INET':
            print("\033[1;96m{} : \033[1;m".format(__global_iface__))
            print(netifaces.ifaddresses(__global_iface__)[netifaces.AF_INET])

        elif _AF == 'AF_LINK':
            print("\033[1;96m{} : \033[1;m".format(__global_iface__))
            print(netifaces.ifaddresses(__global_iface__)[netifaces.AF_LINK])

        elif _AF:
            syntax_err('inet')

        else:
            print("\033[1;96m{} : \033[1;m".format(__global_iface__))
            print(netifaces.ifaddresses(__global_iface__))
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                if not addr['addr'].startswith('fe80'):
                    network = netaddr.IPNetwork("%s/%s" % (addr['addr'],
                                                           addr['netmask']))
                    cidr = network.cidr
                    if address in cidr:
                        if key == 'iface':
                            return iface
                        elif key == 'netmask' and cidr:
                            return str(cidr).split('/')[1]
                        else:
                            return addr[key]

    return None
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:rpi-can-logger    作者:JonnoFTW    | 项目源码 | 文件源码
def get_ip():
    try:
        return ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
    except:
        return "ERROR"
项目:charm-heat    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-nova-cloud-controller    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:cthulhu    作者:sholsapp    | 项目源码 | 文件源码
def main(instances, docker_bridge, docker_container, fixture_root, fixture_name):

    try:
        addrs = netifaces.ifaddresses(docker_bridge)
    except ValueError:
        click.secho('It appears {0} is not a valid newtork interface on this system.'.format(
            docker_bridge), fg='red')
        sys.exit(1)

    try:
        docker_bridge_addr = IPAddress(addrs[netifaces.AF_INET][0]['addr'])
    except IndexError:
        click.secho('It appears {0} does not have an address at this time.'.format(docker_bridge), fg='red')
        sys.exit(1)

    network = list(IPRange(docker_bridge_addr + 1,
                           docker_bridge_addr + 1 + instances - 1))

    if os.path.exists(os.path.join(fixture_root, fixture_name)):
        click.secho('[ERROR] ', fg='red', nl=False)
        click.secho('A fixture named {0} already exists.'.format(fixture_name))
        sys.exit(1)

    fixture_ctx = FixtureContext(fixture_root, fixture_name)

    for instance in range(0, len(network)):
        # TODO(sholsapp): We might want to specify different containers for
        # different instances one day.
        instance_ctx = InstanceContext(
            fixture_ctx.fixture_root, instance, network, docker_container)
        click.secho('Creating instance {0} at {1}... '.format(
            instance_ctx.instance, instance_ctx.node_root), nl=False)
        fixture_ctx.instances.append(instance_ctx)
        click.secho('[GOOD]', fg='green')
    fixture_ctx.render()
项目:dappled    作者:lhon    | 项目源码 | 文件源码
def get_ip_addresses():
    results = []
    for if_name in netifaces.interfaces():
        if if_name == 'lo': continue
        for info in netifaces.ifaddresses(if_name).setdefault(netifaces.AF_INET, []):
            if 'addr' in info:
                results.append(info['addr'])
    if not results:
        return ['127.0.0.1']
    return results

# from notebook/notebookapp.py
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:Legion    作者:MooseDojo    | 项目源码 | 文件源码
def testConnection(self, neighbor):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((neighbor.ip,neighbor.port))
        if result == 0:
            return True
        else:
            return False

    # test to see if we can still communicate to our neighbors
项目:Legion    作者:MooseDojo    | 项目源码 | 文件源码
def getLocalIP():
    default_iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
    default_data = netifaces.ifaddresses(default_iface).setdefault(netifaces.AF_INET, [{'addr':'No IP addr'}])
    for i in default_data:
        return (i['addr'])
项目:Legion    作者:MooseDojo    | 项目源码 | 文件源码
def selectLocalIP():
    ips = list() 
    print ("------------------------")
    i = 1
    for ifaceName in netifaces.interfaces():
        tmp_ips = [i['addr'] for i in netifaces.ifaddresses(ifaceName).setdefault(netifaces.AF_INET, [{'addr':'No IP addr'}] )]
        ips += tmp_ips
        print(str(i) + ": " + str(tmp_ips) + "    (" + ifaceName +")")
        i = i + 1
    print ("------------------------")
    print ("")
    answer = input("Which IP to use as Server IP? ")

    return ips[int(answer)-1]
项目:charm-ceph-osd    作者:openstack    | 项目源码 | 文件源码
def _get_for_address(address, key):
    """Retrieve an attribute of or the physical interface that
    the IP address provided could be bound to.

    :param address (str): An individual IPv4 or IPv6 address without a net
        mask or subnet prefix. For example, '192.168.1.1'.
    :param key: 'iface' for the physical interface name or an attribute
        of the configured interface, for example 'netmask'.
    :returns str: Requested attribute or None if address is not bindable.
    """
    address = netaddr.IPAddress(address)
    for iface in netifaces.interfaces():
        addresses = netifaces.ifaddresses(iface)
        if address.version == 4 and netifaces.AF_INET in addresses:
            addr = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
            cidr = network.cidr
            if address in cidr:
                if key == 'iface':
                    return iface
                else:
                    return addresses[netifaces.AF_INET][0][key]

        if address.version == 6 and netifaces.AF_INET6 in addresses:
            for addr in addresses[netifaces.AF_INET6]:
                network = _get_ipv6_network_from_address(addr)
                if not network:
                    continue

                cidr = network.cidr
                if address in cidr:
                    if key == 'iface':
                        return iface
                    elif key == 'netmask' and cidr:
                        return str(cidr).split('/')[1]
                    else:
                        return addr[key]
    return None
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def map_none(self):
        if self.source_ip == '0.0.0.0':
            try:
                default_gw_if = netifaces.gateways()['default'][netifaces.AF_INET][1]
                self.source_ip = netifaces.ifaddresses(default_gw_if)[netifaces.AF_INET][0]['addr']
            except (OSError, IndexError, KeyError):
                log.critical("Couldn't get interface address. "
                             "Try specifying with '--nat ext:<ip>'.")
                raise
        log.warning('Using internal interface address. Connectivity issues are likely.')
        return PortMappedSocket(self.socket, 'NONE', self.source_ip, self.source_port)
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def _open_socket(self):
        sock = socket.socket(
            socket.AF_INET,  # Internet
            socket.SOCK_DGRAM  # UDP
        )

        sock.bind((self.source_ip, self.source_port))
        log.debug(
            'Socket opened',
            ip=sock.getsockname()[0],
            port=sock.getsockname()[1],
        )
        self.socket = sock
项目:node-agent    作者:Tendrl    | 项目源码 | 文件源码
def is_ipv4_present(interface):
    addr = ni.ifaddresses(interface)
    return ni.AF_INET in addr
项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def internet_addresses():
    """
    Return the info network.
    """
    interface = netifaces.ifaddresses('en0')
    info = interface[netifaces.AF_INET]
    if info:
        return interface[netifaces.AF_INET]
项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def internet_addresses():
    """
    Return the info network.
    """
    interface = netifaces.ifaddresses('en0')
    info = interface[netifaces.AF_INET]
    if info:
        return interface[netifaces.AF_INET]