Python netifaces.AF_INET6 Examples

The following are 30 code examples of netifaces.AF_INET6(). 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 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 #3
Source File: snappy.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_default_gateway_ip():
    """Return the default gateway IP."""
    gateways = netifaces.gateways()
    defaults = gateways.get("default")
    if not defaults:
        return

    def default_ip(family):
        gw_info = defaults.get(family)
        if not gw_info:
            return
        addresses = netifaces.ifaddresses(gw_info[1]).get(family)
        if addresses:
            return addresses[0]["addr"]

    return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6) 
Example #4
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_includes_loopback(self):
        v4_loopback_address = "127.0.0.1"
        v6_loopback_address = "::1"
        patch_interfaces(
            self,
            {
                "lo": {
                    AF_INET: [{"addr": v4_loopback_address}],
                    AF_INET6: [{"addr": v6_loopback_address}],
                }
            },
        )
        self.assertEqual(
            [v4_loopback_address, v6_loopback_address],
            list(get_all_interface_addresses()),
        ) 
Example #5
Source File: network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_all_addresses_for_interface(interface: str) -> Iterable[str]:
    """Yield all IPv4 and IPv6 addresses for an interface as `IPAddress`es.

    IPv4 addresses will be yielded first, followed by IPv6 addresses.

    :param interface: The name of the interface whose addresses we
        should retrieve.
    """
    addresses = netifaces.ifaddresses(interface)
    if netifaces.AF_INET in addresses:
        for inet_address in addresses[netifaces.AF_INET]:
            if "addr" in inet_address:
                yield inet_address["addr"]
    if netifaces.AF_INET6 in addresses:
        for inet6_address in addresses[netifaces.AF_INET6]:
            if "addr" in inet6_address:
                # We know the interface name, so we don't care to keep the
                # interface name on link-local addresses.  Strip those off
                # here.
                yield clean_up_netifaces_address(
                    inet6_address["addr"], interface
                ) 
Example #6
Source File: locations_and_services.py    From expressvpn_leak_testing with MIT License 6 votes vote down vote up
def active(self):
        if not self.enabled():
            return False
        iface = self.interface()
        if not iface:
            return False

        store = _MacOSNetworkHelper.create_dynamic_store()
        # TODO: This doesn't actually report active correctly
        plist = SCDynamicStoreCopyValue(store, "State:/Network/Interface/{}/Link".format(iface))
        if not plist or 'Active' not in plist:
            L.warning("Can't get link state for {}. Got {}".format(self, plist))
            return False

        if not plist['Active']:
            return False

        ifaces = netifaces.ifaddresses(iface)
        return netifaces.AF_INET in ifaces or netifaces.AF_INET6 in ifaces 
Example #7
Source File: ipaddr.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_machine_default_gateway_ip():
    """Return the default gateway IP for the machine."""
    gateways = netifaces.gateways()
    defaults = gateways.get("default")
    if not defaults:
        return

    def default_ip(family):
        gw_info = defaults.get(family)
        if not gw_info:
            return
        addresses = netifaces.ifaddresses(gw_info[1]).get(family)
        if addresses:
            return addresses[0]["addr"]

    return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6) 
Example #8
Source File: test_snappy.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_default_gateway_ip_returns_ipv4_over_ipv6(self):
        gw4_address = factory.make_ipv4_address()
        gw6_address = factory.make_ipv6_address()
        ipv4_address = factory.make_ipv4_address()
        ipv6_address = factory.make_ipv6_address()
        iface = factory.make_name("eth")
        self.patch(netifaces, "gateways").return_value = {
            "default": {
                netifaces.AF_INET: (gw4_address, iface),
                netifaces.AF_INET6: (gw6_address, iface),
            }
        }
        self.patch(netifaces, "ifaddresses").return_value = {
            netifaces.AF_INET: [{"addr": ipv4_address}],
            netifaces.AF_INET6: [{"addr": ipv6_address}],
        }
        self.assertEqual(ipv4_address, snappy.get_default_gateway_ip()) 
Example #9
Source File: network.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        """
        Gather information about network interfaces and write it to the
        sysinfo output.

        @return: A succeeded C{Deferred}.
        """
        device_info = self._get_device_info()
        for info in sorted(device_info, key=itemgetter('interface')):
            interface = info["interface"]
            ipv4_addresses = info["ip_addresses"].get(AF_INET, [])
            ipv6_addresses = info["ip_addresses"].get(AF_INET6, [])
            for addr in ipv4_addresses:
                self._sysinfo.add_header(
                    "IPv4 address for %s" % interface, addr['addr'])
            for addr in ipv6_addresses:
                self._sysinfo.add_header(
                    "IPv6 address for %s" % interface, addr['addr'])

        return succeed(None) 
Example #10
Source File: network.py    From landscape-client with GNU General Public License v2.0 6 votes vote down vote up
def get_ip_addresses(ifaddresses):
    """Return all IP addresses of an interfaces.

    Returns the same structure as L{ifaddresses}, but filtered to keep
    IP addresses only.

    @param ifaddresses: a dict as returned by L{netifaces.ifaddresses} or
        the address data in L{get_active_interfaces}'s output.
    """
    results = {}
    if netifaces.AF_INET in ifaddresses:
        results[netifaces.AF_INET] = ifaddresses[netifaces.AF_INET]
    if netifaces.AF_INET6 in ifaddresses:
        # Ignore link-local IPv6 addresses (fe80::/10).
        global_addrs = [addr for addr in ifaddresses[netifaces.AF_INET6]
                        if not addr['addr'].startswith('fe80:')]
        if global_addrs:
            results[netifaces.AF_INET6] = global_addrs

    return results 
Example #11
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
def ipv6_address_validation(self,
                                ipv6_address: str = 'fd00::1',
                                exit_on_failure: bool = False,
                                exit_code: int = 28,
                                quiet: bool = True) -> bool:
        """
        Validate IPv6 address string
        :param ipv6_address: IPv6 address string (example: 'fd00::1')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 28)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: True if a valid IPv6 address or False if not
        """
        try:
            sock.inet_pton(sock.AF_INET6, ipv6_address)
            return True
        except sock.error:
            if not quiet:
                self.print_error('Failed to validate IPv6 address: ', str(ipv6_address))
            if exit_on_failure:
                exit(exit_code)
            return False 
Example #12
Source File: iscsi.py    From DeepSea with GNU General Public License v3.0 6 votes vote down vote up
def _ip_addresses():
    ip_list = set()
    for iface in netifaces.interfaces():
        if netifaces.AF_INET in netifaces.ifaddresses(iface):
            for link in netifaces.ifaddresses(iface)[netifaces.AF_INET]:
                ip_list.add(link['addr'])
        if netifaces.AF_INET6 in netifaces.ifaddresses(iface):
            for link in netifaces.ifaddresses(iface)[netifaces.AF_INET6]:
                if '%' in link['addr']:
                    continue
                ip_list.add(link['addr'])

    ip_list.discard('::1')
    ip_list.discard('127.0.0.1')

    return list(ip_list) 
Example #13
Source File: pcapdnet.py    From arissploit with GNU General Public License v3.0 6 votes vote down vote up
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, bytes(val.contents.sin6_addr[:]))
            scope = scapy.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs) 
Example #14
Source File: utils.py    From coriolis with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_local_ips():
    ifaces = netifaces.interfaces()
    ret = []
    for iface in ifaces:
        if iface == "lo":
            continue
        addrs = netifaces.ifaddresses(iface)
        ret.append(
            {
                iface: {
                    "ipv4": addrs.get(netifaces.AF_INET),
                    "ipv6": addrs.get(netifaces.AF_INET6),
                },
            }
        )
    return ret 
Example #15
Source File: view.py    From cli with MIT License 6 votes vote down vote up
def best_remote_address():
    """
    Returns the "best" non-localback IP address for the local host, if
    possible.  The "best" IP address is that bound to either the default
    gateway interface, if any, else the arbitrary first interface found.

    IPv4 is preferred, but IPv6 will be used if no IPv4 interfaces/addresses
    are available.
    """
    default_gateway   = net.gateways().get("default", {})
    default_interface = default_gateway.get(net.AF_INET,  (None, None))[1] \
                     or default_gateway.get(net.AF_INET6, (None, None))[1] \
                     or net.interfaces()[0]

    interface_addresses = net.ifaddresses(default_interface).get(net.AF_INET)  \
                       or net.ifaddresses(default_interface).get(net.AF_INET6) \
                       or []

    addresses = [
        address["addr"]
            for address in interface_addresses
             if address.get("addr")
    ]

    return addresses[0] if addresses else None 
Example #16
Source File: pcapdnet.py    From kamene with GNU General Public License v2.0 6 votes vote down vote up
def in6_getifaddr():
      """
      Returns a list of 3-tuples of the form (addr, scope, iface) where
      'addr' is the address of scope 'scope' associated to the interface
      'ifcace'.

      This is the list of all addresses of all interfaces available on
      the system.
      """

      ret = []
      interfaces = get_if_list()
      for i in interfaces:
        addrs = netifaces.ifaddresses(i)
        if netifaces.AF_INET6 not in addrs:
          continue
        for a in addrs[netifaces.AF_INET6]:
          addr = a['addr'].split('%')[0]
          scope = kamene.utils6.in6_getscope(addr)
          ret.append((addr, scope, i))
      return ret 
Example #17
Source File: pcapdnet.py    From kamene with GNU General Public License v2.0 6 votes vote down vote up
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, bytes(val.contents.sin6_addr[:]))
            scope = kamene.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs) 
Example #18
Source File: pcapdnet.py    From arissploit with GNU General Public License v3.0 6 votes vote down vote up
def in6_getifaddr():
      """
      Returns a list of 3-tuples of the form (addr, scope, iface) where
      'addr' is the address of scope 'scope' associated to the interface
      'ifcace'.

      This is the list of all addresses of all interfaces available on
      the system.
      """

      ret = []
      interfaces = get_if_list()
      for i in interfaces:
        addrs = netifaces.ifaddresses(i)
        if netifaces.AF_INET6 not in addrs:
          continue
        for a in addrs[netifaces.AF_INET6]:
          addr = a['addr'].split('%')[0]
          scope = scapy.utils6.in6_getscope(addr)
          ret.append((addr, scope, i))
      return ret 
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: 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 #22
Source File: test_ipaddr.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_machine_default_gateway_ip_returns_ipv4_over_ipv6(self):
        gw4_address = factory.make_ipv4_address()
        gw6_address = factory.make_ipv6_address()
        ipv4_address = factory.make_ipv4_address()
        ipv6_address = factory.make_ipv6_address()
        iface = factory.make_name("eth")
        self.patch(netifaces, "gateways").return_value = {
            "default": {
                netifaces.AF_INET: (gw4_address, iface),
                netifaces.AF_INET6: (gw6_address, iface),
            }
        }
        self.patch(netifaces, "ifaddresses").return_value = {
            netifaces.AF_INET: [{"addr": ipv4_address}],
            netifaces.AF_INET6: [{"addr": ipv6_address}],
        }
        self.assertEqual(ipv4_address, get_machine_default_gateway_ip()) 
Example #23
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 #24
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 #25
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 #26
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
def get_interface_ipv6_gateway(self,
                                   interface_name: str = 'eth0',
                                   exit_on_failure: bool = True,
                                   exit_code: int = 24,
                                   quiet: bool = False) -> Union[None, str]:
        """
        Get IPv6 gateway address on network interface
        :param interface_name: Network interface name (default: 'eth0')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 24)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: IPv6 address string (example: 'fd00::1') or None in case of error
        """
        if interface_name in self._network_interfaces_settings.keys():
            if self._network_interfaces_settings[interface_name]['ipv6-gateway'] is not None:
                return self._network_interfaces_settings[interface_name]['ipv6-gateway']

        return self.get_interface_gateway(interface_name=interface_name,
                                          network_type=AF_INET6,
                                          exit_on_failure=exit_on_failure,
                                          exit_code=exit_code,
                                          quiet=quiet) 
Example #27
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def canonicalize(self, ip_str):
        """
        Parse an IP string for listen to IPAddress content.
        """
        try:
            if ':' in ip_str:
                self.version = 'ipv6'
                if '%' in ip_str:
                    ip_str, scope = ip_str.split('%')
                    self.scope = int(scope)
                self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
            else:
                self.version = 'ipv4'
                self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
        except socket.error as detail:
            if 'illegal IP address' in str(detail):
                self.addr = ip_str
                self.version = 'hostname' 
Example #28
Source File: test_snappy.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_default_gateway_ip_returns_ipv6(self):
        gw_address = factory.make_ipv6_address()
        ipv6_address = factory.make_ipv6_address()
        iface_name = factory.make_name("eth")
        self.patch(netifaces, "gateways").return_value = {
            "default": {netifaces.AF_INET6: (gw_address, iface_name)}
        }
        self.patch(netifaces, "ifaddresses").return_value = {
            netifaces.AF_INET6: [{"addr": ipv6_address}]
        }
        self.assertEqual(ipv6_address, snappy.get_default_gateway_ip()) 
Example #29
Source File: mitm6.py    From mitm6 with GNU General Public License v2.0 5 votes vote down vote up
def setupFakeDns():
    # We bind to port 53 to prevent ICMP port unreachable packets being sent
    # actual responses are sent by scapy
    sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    fulladdr = config.v6addr+ '%' + config.default_if
    addrinfo = socket.getaddrinfo(fulladdr, 53, socket.AF_INET6, socket.SOCK_DGRAM)
    sock.bind(addrinfo[0][4])
    sock.setblocking(0)
    return sock 
Example #30
Source File: test_ipaddr.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_machine_default_gateway_ip_returns_ipv6(self):
        gw_address = factory.make_ipv6_address()
        ipv6_address = factory.make_ipv6_address()
        iface_name = factory.make_name("eth")
        self.patch(netifaces, "gateways").return_value = {
            "default": {netifaces.AF_INET6: (gw_address, iface_name)}
        }
        self.patch(netifaces, "ifaddresses").return_value = {
            netifaces.AF_INET6: [{"addr": ipv6_address}]
        }
        self.assertEqual(ipv6_address, get_machine_default_gateway_ip())