Python socket.if_nametoindex() Examples

The following are 16 code examples of socket.if_nametoindex(). 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 socket , or try the search function .
Example #1
Source File: multicast_checks.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def _create_ipv6_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    intf_name = find_ethernet_interface()
    intf_index = socket.if_nametoindex(intf_name)
    mcast_address = "ff02::abcd:99"
    port = 30000
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
    if platform.system() == "Darwin":
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
    else:
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
    rxsock.bind(("::", port))
    return (txsock, rxsock) 
Example #2
Source File: udp_rx_handler.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, interface_name, local_port, ipv4, multicast_address, remote_address,
                 receive_function, log, log_id):
        self._interface_name = interface_name
        self._local_port = local_port
        self._ipv4 = ipv4                             # IPv4 if True, IPv6 if False
        self._remote_address = remote_address
        self._multicast_address = multicast_address   # Unicast socket if None
        self._receive_function = receive_function
        self._log = log
        self._log_id = log_id
        self._local_ipv4_address = utils.interface_ipv4_address(interface_name)
        self._local_ipv6_address = utils.interface_ipv6_address(interface_name)
        try:
            self._interface_index = socket.if_nametoindex(interface_name)
        except (IOError, OSError) as err:
            self.warning("Could determine index of interface %s: %s", interface_name, err)
            self._interface_index = None
        if ipv4:
            if self._multicast_address:
                self.sock = self.create_socket_ipv4_rx_mcast()
            else:
                self.sock = self.create_socket_ipv4_rx_ucast()
        else:
            if self._multicast_address:
                self.sock = self.create_socket_ipv6_rx_mcast()
            else:
                self.sock = self.create_socket_ipv6_rx_ucast()
        if self.sock:
            scheduler.SCHEDULER.register_handler(self) 
Example #3
Source File: wsdd.py    From wsdd with MIT License 6 votes vote down vote up
def init_v4(self):
        idx = socket.if_nametoindex(self.interface.name)
        self.multicast_address = (WSD_MCAST_GRP_V4, WSD_UDP_PORT)

        # v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx }
        mreq = (
            socket.inet_pton(self.family, WSD_MCAST_GRP_V4) +
            socket.inet_pton(self.family, self.address) +
            struct.pack('@I', idx))
        self.recv_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        try:
            self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT))
        except OSError:
            self.recv_socket.bind(('', WSD_UDP_PORT))

        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq)
        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
        self.send_socket.setsockopt(
            socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, args.hoplimit)

        self.listen_address = (self.address, WSD_HTTP_PORT) 
Example #4
Source File: eap_proxy.py    From eap_proxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def if_nametoindex(ifname):
        return _if_nametoindex(to_utf8(ifname))


### Sockets / Network Interfaces 
Example #5
Source File: eap_proxy.py    From eap_proxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addsockaddr(sock, address):
    """Configure physical-layer multicasting or promiscuous mode for `sock`.
       If `addr` is None, promiscuous mode is configured. Otherwise `addr`
       should be a tuple of up to 8 bytes to configure that multicast address.
    """
    # pylint:disable=attribute-defined-outside-init
    mreq = struct_packet_mreq()
    mreq.mr_ifindex = if_nametoindex(getifname(sock))
    if address is None:
        mreq.mr_type = PACKET_MR_PROMISC
    else:
        mreq.mr_type = PACKET_MR_MULTICAST
        mreq.mr_alen = len(address)
        mreq.mr_address = address
    sock.setsockopt(SOL_PACKET, PACKET_ADD_MEMBERSHIP, mreq) 
Example #6
Source File: test_command_line_ping3.py    From ping3 with MIT License 5 votes vote down vote up
def test_interface(self):
        with patch("sys.stdout", new=io.StringIO()) as fake_out:
            try:
                route_cmd = os.popen("ip -o -4 route show to default")
                default_route = route_cmd.read()
            finally:
                route_cmd.close()
            my_interface = default_route.split()[4]
            try:
                socket.if_nametoindex(my_interface)  # test if the interface exists.
            except OSError:
                self.fail('Interface Name Error: {}'.format(my_interface))
            command_line_ping3.main(['-I', my_interface, 'example.com'])
            self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*") 
Example #7
Source File: test_ping3.py    From ping3 with MIT License 5 votes vote down vote up
def test_ping_interface(self):
        try:
            route_cmd = os.popen("ip -o -4 route show to default")
            default_route = route_cmd.read()
        finally:
            route_cmd.close()
        my_interface = default_route.split()[4]
        try:
            socket.if_nametoindex(my_interface)  # test if the interface exists.
        except OSError:
            self.fail('Interface Name Error: {}'.format(my_interface))
        dest_addr = "example.com"
        delay = ping3.ping(dest_addr, interface=my_interface)
        self.assertIsInstance(delay, float) 
Example #8
Source File: test_ping3.py    From ping3 with MIT License 5 votes vote down vote up
def test_verbose_ping_interface(self):
        with patch("sys.stdout", new=io.StringIO()) as fake_out:
            try:
                route_cmd = os.popen("ip -o -4 route show to default")
                default_route = route_cmd.read()
            finally:
                route_cmd.close()
            my_interface = default_route.split()[4]
            try:
                socket.if_nametoindex(my_interface)  # test if the interface exists.
            except OSError:
                self.fail('Interface Name Error: {}'.format(my_interface))
            dest_addr = "example.com"
            ping3.verbose_ping(dest_addr, interface=my_interface)
            self.assertRegex(fake_out.getvalue(), r".*[0-9]+ms.*") 
Example #9
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testInterfaceNameIndex(self):
        interfaces = socket.if_nameindex()
        for index, name in interfaces:
            self.assertIsInstance(index, int)
            self.assertIsInstance(name, str)
            # interface indices are non-zero integers
            self.assertGreater(index, 0)
            _index = socket.if_nametoindex(name)
            self.assertIsInstance(_index, int)
            self.assertEqual(index, _index)
            _name = socket.if_indextoname(index)
            self.assertIsInstance(_name, str)
            self.assertEqual(name, _name) 
Example #10
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testInvalidInterfaceNameIndex(self):
        # test nonexistent interface index/name
        self.assertRaises(OSError, socket.if_indextoname, 0)
        self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
        # test with invalid values
        self.assertRaises(TypeError, socket.if_nametoindex, 0)
        self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') 
Example #11
Source File: test_socket.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testInterfaceNameIndex(self):
        interfaces = socket.if_nameindex()
        for index, name in interfaces:
            self.assertIsInstance(index, int)
            self.assertIsInstance(name, str)
            # interface indices are non-zero integers
            self.assertGreater(index, 0)
            _index = socket.if_nametoindex(name)
            self.assertIsInstance(_index, int)
            self.assertEqual(index, _index)
            _name = socket.if_indextoname(index)
            self.assertIsInstance(_name, str)
            self.assertEqual(name, _name) 
Example #12
Source File: test_socket.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testInvalidInterfaceNameIndex(self):
        # test nonexistent interface index/name
        self.assertRaises(OSError, socket.if_indextoname, 0)
        self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
        # test with invalid values
        self.assertRaises(TypeError, socket.if_nametoindex, 0)
        self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') 
Example #13
Source File: wsdd.py    From wsdd with MIT License 5 votes vote down vote up
def init_v6(self):
        idx = socket.if_nametoindex(self.interface.name)
        self.multicast_address = (WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0x575C, idx)

        # v6: member_request = { multicast_addr, intf_idx }
        mreq = (
            socket.inet_pton(self.family, WSD_MCAST_GRP_V6) +
            struct.pack('@I', idx))
        self.recv_socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
        self.recv_socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

        # bind to network interface, i.e. scope and handle OS differences,
        # see Stevens: Unix Network Programming, Section 21.6, last paragraph
        try:
            self.recv_socket.bind((WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0, idx))
        except OSError:
            self.recv_socket.bind(('::', 0, 0, idx))

        self.send_socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
        self.send_socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, args.hoplimit)
        self.send_socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, idx)

        self.transport_address = '[{0}]'.format(self.address)
        self.listen_address = (self.address, WSD_HTTP_PORT, 0, idx) 
Example #14
Source File: test_socket.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testInterfaceNameIndex(self):
        interfaces = socket.if_nameindex()
        for index, name in interfaces:
            self.assertIsInstance(index, int)
            self.assertIsInstance(name, str)
            # interface indices are non-zero integers
            self.assertGreater(index, 0)
            _index = socket.if_nametoindex(name)
            self.assertIsInstance(_index, int)
            self.assertEqual(index, _index)
            _name = socket.if_indextoname(index)
            self.assertIsInstance(_name, str)
            self.assertEqual(name, _name) 
Example #15
Source File: test_socket.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testInvalidInterfaceNameIndex(self):
        # test nonexistent interface index/name
        self.assertRaises(OSError, socket.if_indextoname, 0)
        self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
        # test with invalid values
        self.assertRaises(TypeError, socket.if_nametoindex, 0)
        self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') 
Example #16
Source File: _posix.py    From ifaddr with MIT License 4 votes vote down vote up
def get_adapters(include_unconfigured=False):

    addr0 = addr = ctypes.POINTER(ifaddrs)()
    retval = libc.getifaddrs(ctypes.byref(addr))
    if retval != 0:
        eno = ctypes.get_errno()
        raise OSError(eno, os.strerror(eno))

    ips = collections.OrderedDict()

    def add_ip(adapter_name, ip):
        if not adapter_name in ips:
            try:
                index = socket.if_nametoindex(adapter_name)
            except (OSError, AttributeError):
                index = None
            ips[adapter_name] = shared.Adapter(adapter_name, adapter_name, [],
                                               index=index)
        if ip is not None:
            ips[adapter_name].ips.append(ip)


    while addr:
        name = addr[0].ifa_name
        if sys.version_info[0] > 2:
            name = name.decode(encoding='UTF-8')
        ip = shared.sockaddr_to_ip(addr[0].ifa_addr)
        if ip:
            if addr[0].ifa_netmask and not addr[0].ifa_netmask[0].sa_familiy:
                addr[0].ifa_netmask[0].sa_familiy = addr[0].ifa_addr[0].sa_familiy
            netmask = shared.sockaddr_to_ip(addr[0].ifa_netmask)
            if isinstance(netmask, tuple):
                netmask = netmask[0]
                if sys.version_info[0] > 2:
                    netmaskStr = str(netmask)
                else:
                    netmaskStr = unicode(netmask)
                prefixlen = shared.ipv6_prefixlength(ipaddress.IPv6Address(netmaskStr))
            else:
                if sys.version_info[0] > 2:
                    netmaskStr = str('0.0.0.0/' + netmask)
                else:
                    netmaskStr = unicode('0.0.0.0/' + netmask)
                prefixlen = ipaddress.IPv4Network(netmaskStr).prefixlen
            ip = shared.IP(ip, prefixlen, name)
            add_ip(name, ip)
        else:
            if include_unconfigured:
                add_ip(name, None)
        addr = addr[0].ifa_next

    libc.freeifaddrs(addr0)

    return ips.values()