Python netifaces.interfaces() Examples

The following are 30 code examples of netifaces.interfaces(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module netifaces , or try the search function .
Example #1
Source File: topology.py    From InsightAgent with Apache License 2.0 7 votes vote down vote up
def get_interfaces():

    interfaces = netifaces.interfaces()
    interfaces.remove('lo')

    out_interfaces = dict()

    for interface in interfaces:
        addrs = netifaces.ifaddresses(interface)
        out_addrs = dict()
        if netifaces.AF_INET in addrs.keys():
            out_addrs["ipv4"] = addrs[netifaces.AF_INET]
        if netifaces.AF_INET6 in addrs.keys():
            out_addrs["ipv6"] = addrs[netifaces.AF_INET6]
        out_interfaces[interface] = out_addrs

    return out_interfaces 
Example #2
Source File: net.py    From pykit with MIT License 7 votes vote down vote up
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 
Example #3
Source File: _net.py    From flocker with Apache License 2.0 7 votes vote down vote up
def get_all_ips():
    """
    Find all IPs for this machine.

    :return: ``set`` of IP addresses (``IPAddress``).
    """
    ips = set()
    interfaces = netifaces.interfaces()
    for interface in interfaces:
        addresses = netifaces.ifaddresses(interface)
        for address_family in (netifaces.AF_INET, netifaces.AF_INET6):
            family_addresses = addresses.get(address_family)
            if not family_addresses:
                continue
            for address in family_addresses:
                ips.add(ipaddress_from_string(address['addr']))
    return ips 
Example #4
Source File: fakenet.py    From flare-fakenet-ng with Apache License 2.0 6 votes vote down vote up
def get_ips(self, ipvers, iface=None):
        """Return IP addresses bound to local interfaces including loopbacks.

        Parameters
        ----------
        ipvers : list(int)
            IP versions desired (4, 6, or both)
        iface : str or NoneType
            Optional interface to limit the query
        returns:
            list(str): IP addresses as requested
        """
        if not all(ver in self._valid_ipvers for ver in ipvers):
            raise ValueError('Only IP versions 4 and 6 are supported')

        if iface and (iface not in self.ifaces):
            raise ValueError('Unrecognized iface %s' % (iface))

        downselect = [i for i in self.ips if i.ver in ipvers]
        if iface:
            downselect = [i for i in downselect if i.iface == iface]
        return [i.ip for i in downselect] 
Example #5
Source File: client-test.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #6
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def interfaces(self):
        if self.homebrewNetifaces:
            import array
            import fcntl

            maxInterfaces = 128
            bufsiz = maxInterfaces * 40
            nullByte = b'\0'

            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ifNames = array.array('B', nullByte * bufsiz)
            ifNameLen = struct.unpack('iL', fcntl.ioctl(
                s.fileno(),
                0x8912, # SIOCGIFCONF
                struct.pack('iL', bufsiz, ifNames.buffer_info()[0])
            ))[0]

            if ifNameLen % self.ifNameStructLen != 0:
                print('Do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                sys.exit(1)

            ifNames = ifNames.tostring()
            for i in range(0, ifNameLen, self.ifNameStructLen):
                name      = ifNames[i:i+16].split(nullByte, 1)[0].decode()
                if not name:
                    print('Cannot determine interface name: do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                    sys.exit(1)
                ip        = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8915, struct.pack('256s', str(name)))[20:24]) # SIOCGIFADDR
                netmask   = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x891b, struct.pack('256s', str(name)))[20:24]) # SIOCGIFNETMASK
                broadcast = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8919, struct.pack('256s', str(name)))[20:24]) # SIOCGIFBRDADDR
                hwaddr    = ':'.join(['%02x' % ord(char) for char in fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8927, struct.pack('256s', str(name)))[18:24]]) # SIOCGIFHWADDR
                self.interfaceAttrs[name] = {Netifaces.AF_LINK: [{'addr': hwaddr}], Netifaces.AF_INET: [{'addr': ip, 'netmask': netmask, 'broadcast': broadcast}]}
            return self.interfaceAttrs.keys()
        else:
            import netifaces
            return netifaces.interfaces() 
Example #7
Source File: engine.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def default_physical_interface(self):
        # When simulated interfaces are disabled, the interface names on nodes correspond to real
        # interfaces on the host platform.
        # When simulated interface are enabled, the interface names on nodes are "fake" i.e. they do
        # not correspond to real interfaces on the host platform. All these simulated interfaces
        # actually run on a single real interface, referred to as the physical interface. Traffic to
        # and from different simulated interfaces are distinguished by using different multicast
        # addresses and port numbers for each simulated interface.
        # Pick the first interface with a broadcast IPv4 address (if any) as the default.
        for intf_name in netifaces.interfaces():
            addresses = netifaces.ifaddresses(intf_name)
            if netifaces.AF_INET in addresses:
                ipv4_addresses = addresses[netifaces.AF_INET]
                for ipv4_address in ipv4_addresses:
                    if 'broadcast' in ipv4_address:
                        return intf_name
        print("Cannot pick default physical interface: no broadcast interface found")
        sys.exit(1) 
Example #8
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def addListener(self, addr, port, service):
        if self.isBroadcast(addr):
            self.etherAddrs[addr] = self.broadcastIpToMac(addr)
        elif self.isMulticast(addr):
            self.etherAddrs[addr] = self.multicastIpToMac(addr)
        else:
            # unicast -- we don't know yet which IP we'll want to send to
            self.etherAddrs[addr] = None

        # Set up the receiving socket and corresponding IP and interface information.
        # One receiving socket is required per multicast address.
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        for interface in self.interfaces:
            (ifname, mac, ip, netmask) = self.getInterface(interface)

            # Add this interface to the receiving socket's list.
            if self.isBroadcast(addr):
                rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            elif self.isMulticast(addr):
                packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip))
                rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress)

            # Generate a transmitter socket. Each interface
            # requires its own transmitting socket.
            if interface not in self.noTransmitInterfaces:
                tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
                tx.bind((ifname, 0))

                self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service})

        rx.bind((addr, port))
        self.receivers.append(rx) 
Example #9
Source File: client-test2.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #10
Source File: nat.py    From pyquarkchain with MIT License 6 votes vote down vote up
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
    """
    For a given UPnP device, return the internal IP address of this host machine that can
    be used for a NAT mapping.
    """
    parsed_url = urlparse(upnp_dev.location)
    # Get an ipaddress.IPv4Network instance for the upnp device's network.
    upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False)
    for iface in netifaces.interfaces():
        for family, addresses in netifaces.ifaddresses(iface).items():
            # TODO: Support IPv6 addresses as well.
            if family != netifaces.AF_INET:
                continue
            for item in addresses:
                if ipaddress.ip_address(item["addr"]) in upnp_dev_net:
                    return item["addr"]
    raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname) 
Example #11
Source File: fprobe_container_crawler.py    From agentless-system-crawler with Apache License 2.0 6 votes vote down vote up
def crawl(self, container_id, avoid_setns=False, **kwargs):
        """
          Start flow probe + data collector pairs on the interfaces of
          the given container; collect the files that the collector
          wrote and return their content.
        """
        if time.time() > FprobeContainerCrawler.next_cleanup:
            # we won't run the cleanup of old files the first time
            # but let the crawler do one full round of picking up
            # relevant files and then only we do a proper cleaning
            if FprobeContainerCrawler.next_cleanup > 0:
                FprobeContainerCrawler.remove_old_files(**kwargs)

            self.cleanup(**kwargs)
            FprobeContainerCrawler.next_cleanup = time.time() + 30

        ifnames = self.start_container_fprobes(container_id, avoid_setns,
                                               **kwargs)

        return self.collect_files(container_id, ifnames, **kwargs) 
Example #12
Source File: ctprobe_container_crawler.py    From agentless-system-crawler with Apache License 2.0 6 votes vote down vote up
def cleanup(self, **kwargs):
        """
          Check the available interfaces on the host versus those ones we
          have flow probes running and remove those where the interface has
          disappeared. We clean up the files with netlink data that were
          written for those interfaces.
        """
        devices = netifaces.interfaces()

        lst = []

        for ifname in CTProbeContainerCrawler.ifaces_monitored:
            if ifname not in devices:
                self.remove_datafiles(ifname, **kwargs)
            else:
                lst.append(ifname)

        CTProbeContainerCrawler.ifaces_monitored = lst 
Example #13
Source File: GEventNetworkManager.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def connectivity_request(self):
        """Handles connectivity requests"""
        # please note: normally we get an rcat argument, default: rcat=0
        with Promise() as p:
            blacklist = ['lo']
            interfaces = netifaces.interfaces()

            interface = next((x for x in interfaces if (x not in blacklist)),
                             None)

            if interface is None:
                p.reject(InterfaceNotFoundException(
                    "No interfaces found matching request"))
            else:
                p.fulfill((self._get_interface(interface), 0))

        return p 
Example #14
Source File: GEventNetworkManager.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _get_interface(self, name):
        """Returns an Interface object identified by name

        :param name: name of interface
        :return Interface: interface
        :raise UnknownInterface: if interface was not found
        """
        if name not in netifaces.interfaces():
            raise InterfaceNotFoundException("%s was not found" % name)
        else:
            ifaddresses = netifaces.ifaddresses(name)
            addresses = self._get_addresses_from_ifaddresses(ifaddresses)
            try:
                hwaddress = ifaddresses[netifaces.AF_LINK][0]["addr"]
            except (IndexError, KeyError):
                self.logger.debug("No hardware address found for %s!", name)
                hwaddress = None
            return Interface(name=name,
                             addresses=addresses,
                             hwaddress=hwaddress) 
Example #15
Source File: client.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #16
Source File: addressmapper.py    From supvisors with Apache License 2.0 6 votes vote down vote up
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 [] 
Example #17
Source File: endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _guess_lan_address(self, interfaces, default=None):
        """
        Chooses the most likely Interface instance out of INTERFACES to use as our LAN address.

        INTERFACES can be obtained from _get_interface_addresses()
        DEFAULT is used when no appropriate Interface can be found
        """
        assert isinstance(interfaces, list), type(interfaces)
        blacklist = ["127.0.0.1", "0.0.0.0", "255.255.255.255"]

        # prefer interfaces where we have a broadcast address
        for interface in interfaces:
            if interface.broadcast and interface.address and interface.address not in blacklist:
                return interface

        # Exception for virtual machines/containers
        for interface in interfaces:
            if interface.address and interface.address not in blacklist:
                return interface

        self._netifaces_failed = True
        return default 
Example #18
Source File: localif.py    From pscheduler with Apache License 2.0 6 votes vote down vote up
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(ipaddress.ip_network(unicode(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(ipaddress.ip_network(unicode(ifaddr['addr'].split('%')[0]))) 
Example #19
Source File: zeroconf.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def find(cls, zc=None, timeout=5, interfaces=InterfaceChoice.All):
        """
        Return all of the advertised services on any local networks.

        :param zc: Zeroconf() instance.  Pass in if already have an
                instance running or if non-default interfaces are needed
        :param timeout: seconds to wait for any responses
        :return: tuple of service type strings
        """
        local_zc = zc or Zeroconf(interfaces=interfaces)
        listener = cls()
        browser = ServiceBrowser(
            local_zc, '_services._dns-sd._udp.local.', listener=listener)

        # wait for responses
        time.sleep(timeout)

        # close down anything we opened
        if zc is None:
            local_zc.close()
        else:
            browser.cancel()

        return tuple(sorted(listener.found_services)) 
Example #20
Source File: wol.py    From epoptes with GNU General Public License v3.0 6 votes vote down vote up
def get_broadcast_list():
    """Return all broadcast addresses.
    E.g. WOL messages need to be sent from all NICs.
    """
    brlist = ['<broadcast>']
    ifaces = [iface for iface in netifaces.interfaces() if iface != 'lo']
    for ifname in ifaces:
        # An interface can have more than one address, even within the
        # same family (AF_INET), or none, so check this case too.
        addresses = netifaces.ifaddresses(ifname)
        if netifaces.AF_INET not in addresses:
            continue
        for addr in addresses[netifaces.AF_INET]:
            if 'broadcast' in addr:
                brlist.append(addr['broadcast'])
    return brlist 
Example #21
Source File: wsgi.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _get_addresses(self, family):
        try:
            return self.__cached_addresses[family]
        except KeyError:
            from netifaces import interfaces, ifaddresses

            addresses = self.__cached_addresses[family] = set()

            for interface in interfaces():
                try:
                    ifdata = ifaddresses(interface)[family]
                    ifaddrs = [x.split("%")[0] for x in pluck("addr", ifdata)]
                    addresses.update(ifaddrs)
                except KeyError:
                    pass

            return addresses 
Example #22
Source File: GEventNetworkManager.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _get_addresses(self, iface=None):
        """Get addresses of a given interface

        :param iface: name of interface
        :return: list of addresses
        """

        if iface is None:
            interfaces = netifaces.interfaces()
        else:
            interfaces = [iface]

        addresses = []

        for interface in interfaces:
            n_addresses = netifaces.ifaddresses(interface)
            addresses += self._get_addresses_from_ifaddresses(n_addresses)

        # check if array has duplicates
        # addresses = list(set(addresses))

        return addresses 
Example #23
Source File: localsubnet.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
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)

            pairs = []

            for ifaddr in ifaddrs[netifaces.AF_INET] \
                if netifaces.AF_INET in ifaddrs else []:
                self.cidrs.append(ipaddress.IPv4Network(
                    unicode("%s/%s" % (ifaddr["addr"], ifaddr["netmask"])),
                    strict=False  # Don't complain about host bits being set.
                ))

            for ifaddr in ifaddrs[netifaces.AF_INET6] \
                if netifaces.AF_INET6 in ifaddrs else []:
                self.cidrs.append(ipaddress.IPv6Network(
                    unicode("%s/%s" % (
                        ifaddr["addr"].split("%")[0],
                        ipv6_netmask_size(ifaddr["netmask"]))),
                    strict=False  # Don't complain about host bits being set.
                )) 
Example #24
Source File: misphere.py    From pysphere with MIT License 5 votes vote down vote up
def register_tcp(self, params={}):
        for e in ni.interfaces():
            if e.lower().startswith('w'):
                ip = ni.ifaddresses(e)[ni.AF_INET][0]['addr']
                if ip.startswith("192.168.42."):
                    break
        params = {"param": ip, "type": "TCP"}
        self.send(REGISTER_TCP, params)
        return self.recv() 
Example #25
Source File: core.py    From pina-colada with MIT License 5 votes vote down vote up
def __init__(self):
        self.interfaces = self.get_available_interfaces()
        self.default_iface = self.interfaces[0]
        self.localIP = self.get_local_ip(self.default_iface)
        self.network = network.init_network(self)
        self.cur = self.network.cur
        self.categories = None
        self.loaded_capabilities = {}
        self.cnc = self.localIP  # TODO 
Example #26
Source File: zeroconf.py    From apple_bleee with GNU General Public License v3.0 5 votes vote down vote up
def get_all_addresses(address_family):
    return list(set(
        addr['addr']
        for iface in netifaces.interfaces()
        for addr in netifaces.ifaddresses(iface).get(address_family, [])
        if addr.get('netmask') != HOST_ONLY_NETWORK_MASK
    )) 
Example #27
Source File: core.py    From pina-colada with MIT License 5 votes vote down vote up
def set_interface(self, iface):
        if iface in ni.interfaces() and ni.AF_INET in ni.ifaddresses(iface):
            self.default_iface = iface
            self.localIP = self.get_local_ip(self.default_iface)
            return True
        else:
            return None 
Example #28
Source File: test_ifaddr.py    From ifaddr with MIT License 5 votes vote down vote up
def test_netifaces_compatibility():
    interfaces = ifaddr.netifaces.interfaces()
    assert interfaces == netifaces.interfaces()
    # TODO: implement those as well
    # for interface in interfaces:
    #     print(interface)
    #     assert ifaddr.netifaces.ifaddresses(interface) == netifaces.ifaddresses(interface)
    # assert ifaddr.netifaces.gateways() == netifaces.gateways() 
Example #29
Source File: network.py    From black-widow with GNU General Public License v3.0 5 votes vote down vote up
def get_interfaces():
    """
    Get all network interfaces
    :rtype: list
    """
    return ni.interfaces() 
Example #30
Source File: ssh_login.py    From pythonpentest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_interfaces():
    interfaces = netifaces.interfaces()
    return interfaces