Python socket.AF_PACKET Examples

The following are 22 code examples of socket.AF_PACKET(). 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: utils.py    From HoneyBot with MIT License 6 votes vote down vote up
def get_mac_address_of_interface(interface):
    """
    :param interface: The friendly name of a network interface
    :return: the MAC address associated with that interface
    """
    for k,v in psutil.net_if_addrs().items():
        if interface == k:
            for item in v:
                try:
                    if item.family == socket.AF_LINK:
                        return item.address
                except AttributeError:
                    # Linux
                    if item.family == socket.AF_PACKET:
                        return item.address
    return None 
Example #2
Source File: host_ethernet.py    From halucinator with GNU General Public License v3.0 6 votes vote down vote up
def start(interface, emu_rx_port=5556, emu_tx_port=5555, msg_id=1073905664):
    global __run_server
    global __host_socket
    # Open socket to send raw frames on ethernet adapter
    os.system('ip link set %s promisc on' % interface)  # Set to permisucous
    # os.system('ethtool -K %s tx off' % interface)

    ETH_P_ALL = 3
    __host_socket = socket.socket(
        socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
    __host_socket.bind((interface, 0))

    print("Starting Servers")
    emu_rx_process = Process(target=rx_from_emulator,
                             args=(emu_rx_port, interface)).start()
    emu_tx_process = Process(
        target=rx_from_host, args=(emu_tx_port, msg_id)).start()
    try:
        while (1):
            time.sleep(0.1)
    except KeyboardInterrupt:
        __run_server = False
    emu_rx_process.join()
    emu_tx_process.join() 
Example #3
Source File: example_list_network_interfaces.py    From libnl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def main():
    """Main function called upon script execution."""
    # First open a socket to the kernel. Same one used for sending and receiving.
    sk = nl_socket_alloc()  # Creates an `nl_sock` instance.
    ret = nl_connect(sk, NETLINK_ROUTE)  # Create file descriptor and bind socket.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_connect() returned {0} ({1})'.format(ret, reason))

    # Next we send the request to the kernel.
    rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)
    ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_send_simple() returned {0} ({1})'.format(ret, reason))
    print('Sent {0} bytes to the kernel.'.format(ret))

    # Finally we'll retrieve the kernel's answer, process it, and call any callbacks attached to the `nl_sock` instance.
    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, None)  # Add callback to the `nl_sock` instance.
    ret = nl_recvmsgs_default(sk)  # Get kernel's answer, and call attached callbacks.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_recvmsgs_default() returned {0} ({1})'.format(ret, reason)) 
Example #4
Source File: xcon.py    From vrnetlab with MIT License 6 votes vote down vote up
def __init__(self, raw_intf = 'eth1', listen_port=10001):
        self.logger = logging.getLogger()
        # setup TCP side
        self.s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        self.s.bind(('::0', listen_port))
        self.s.listen(1)
        self.tcp = None

        # track current state of TCP side tunnel. 0 = reading size, 1 = reading packet
        self.tcp_state = 0
        self.tcp_buf = b''
        self.tcp_remaining = 0

        # setup raw side
        self.raw = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
        self.raw.bind((raw_intf, 0))
        # don't block
        self.raw.setblocking(0) 
Example #5
Source File: dnsmasploit.py    From raw-packet with MIT License 6 votes vote down vote up
def send_dhcpv6_solicit():
    Client_DUID = dhcpv6r.get_duid(macsrc)
    request_options = [23, 24]

    pkt = dhcpv6r.make_solicit_packet(ethernet_src_mac=macsrc,
                                      ipv6_src=ipv6src_link,
                                      transaction_id=randint(1, 16777215),
                                      client_identifier=Client_DUID,
                                      option_request_list=request_options)
    try:
        SOCK = socket(AF_PACKET, SOCK_RAW)
        SOCK.bind((current_network_interface, 0))
        SOCK.send(pkt)
        print(Base.c_info + 'Send Solicit request to: [ff02::1:2]:547')
        SOCK.close()
    except:
        print(Base.c_error + 'Do not send Solicit request.')
        exit(1) 
Example #6
Source File: ethernet_virt_hub.py    From halucinator with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, interface, enable_rx=False):
        Thread.__init__(self)
        self.interface = interface
        self.__stop = Event()
        self.enable_rx = enable_rx

        os.system('ip link set %s promisc on' %
                  interface)  # Set to permisucous
        ETH_P_ALL = 3
        self.host_socket = socket.socket(
            socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
        self.host_socket.bind((interface, 0))
        self.host_socket.settimeout(1.0)
        self.handler = None 
Example #7
Source File: sniffer.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def eth_addr (a) :
    b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5]))
    return b

#create a AF_PACKET type raw socket (thats basically packet level)
#define ETH_P_ALL    0x0003          /* Every packet (be careful!!!) */ 
Example #8
Source File: test_nl_send_simple.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_full(tcp_server, monkeypatch):
    r"""Diff of C code (from test_bare()) to test against.

    --- test_bare.c	2015-02-08 12:43:15.543135855 -0800
    +++ test_full.c	2015-02-08 12:43:08.533183752 -0800
    @@ -13,10 +13,11 @@
             struct nl_sock *sk = nl_socket_alloc();
             nl_connect(sk, NETLINK_ROUTE);
             sk->s_fd = fd;
    -        sk->s_local.nl_pid = 0;
    -        sk->s_seq_next = 0;
    +        sk->s_local.nl_pid = 1234;
    +        sk->s_seq_next = 10;

    -        int ret = nl_send_simple(sk, RTM_GETLINK, 0, NULL, 0);
    +        struct rtgenmsg rt_hdr = { .rtgen_family = AF_PACKET, };
    +        int ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));

             printf("Bytes: %d\n", ret);
             return 0;
    """
    monkeypatch.setattr(libnl.socket_, 'generate_local_port', lambda: 1234)

    sk = nl_socket_alloc()
    nl_connect(sk, NETLINK_ROUTE)
    sk.socket_instance.close()
    sk.socket_instance = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.socket_instance.connect(tcp_server.server.server_address)
    sk.s_local.nl_pid = 1234
    sk.s_seq_next = 10
    rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)

    assert 20 == nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
    assert 1 == len(tcp_server.data)
    assert b'FAAAABIABQMKAAAA0gQAABEAAAA=' == base64.b64encode(buffer(tcp_server.data[0]))
    nl_socket_free(sk) 
Example #9
Source File: wsdd.py    From wsdd with MIT License 5 votes vote down vote up
def enumerate(self):
        super().enumerate()

        kernel = (0, 0)
        req = struct.pack('@IHHIIB', NLM_HDR_LEN + 1, self.RTM_GETADDR,
                          NLM_F_REQUEST | NLM_F_DUMP, 1, os.getpid(),
                          socket.AF_PACKET)
        self.socket.sendto(req, kernel) 
Example #10
Source File: sample_router.py    From ryu with Apache License 2.0 5 votes vote down vote up
def _arp_loop(self):
        try:
            with contextlib.closing(
                socket.socket(
                    socket.AF_PACKET, socket.SOCK_RAW,
                    socket.htons(ether.ETH_TYPE_ARP))) as packet_socket:
                packet_socket.bind((self.interface.device_name,
                                    socket.htons(ether.ETH_TYPE_ARP),
                                    socket.PACKET_BROADCAST,
                                    arp.ARP_HW_TYPE_ETHERNET,
                                    mac_lib.BROADCAST))
                self._arp_loop_socket(packet_socket)
        except greenlet.GreenletExit:
            # suppress thread.kill exception
            pass 
Example #11
Source File: HappyPacketProcess.py    From happy with Apache License 2.0 5 votes vote down vote up
def Sniffer(packetList, e):
    logger = multiprocessing.get_logger()
    snifferSocket = socket.socket(
        socket.AF_PACKET,
        socket.SOCK_RAW,
        socket.ntohs(0x0003)
    )
    snifferSocket.bind((options['interface'], 0))

    logger.info("Sniffer and process packets, Press Ctrl-C to stop.")

    while True:
        packets = snifferSocket.recvfrom(65535)
        packet = packets[0]
        ethernetFrame = EthernetFrame()
        ethernetFrame.Decode(packet)

        if ethernetFrame.ethProto == 8:
            ipPacket = IPv4Packet()
            ipPacket.Decode(ethernetFrame.payload)

            if ipPacket.ipProtocol == 6:
                tcpPacket = TCPPacket()
                tcpPacket.Decode(ipPacket.payload)
            else:
                continue

        else:
            continue

        packetDic = MergeDicts(ethernetFrame.GetEthernetHeaderDic(), ipPacket.GetIpv4HeaderDic(),
                               tcpPacket.GetTcpHeaderDic())
        logger.debug(packetDic)
        snifferFilter = Filter(packetDic, options)
        if snifferFilter.run() is True:
            continue
        print packetDic
        packetList.append(packetDic)
        e.set()

    snifferSocket.close() 
Example #12
Source File: dhcp_starvation.py    From raw-packet with MIT License 5 votes vote down vote up
def send_dhcp_discover():
    sleep(1)
    base.print_info("Sending DHCP discover packets...")
    base.print_info("Delay between DISCOVER packets: ", str(args.delay), " sec.")
    base.print_info("Start sending packets: ", str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
    discover_raw_socket = socket(AF_PACKET, SOCK_RAW)
    discover_raw_socket.bind((listen_network_interface, 0))

    try:
        while True:
            client_mac = eth.make_random_mac()
            transaction_id = randint(1, 4294967295)
            discover_raw_socket.send(dhcp.make_discover_packet(ethernet_src_mac=your_mac_address,
                                                               client_mac=client_mac,
                                                               transaction_id=transaction_id,
                                                               relay_agent_ip=your_ip_address))
            transactions[transaction_id] = client_mac
            if int(time() - start_time) > args.timeout:
                if ack_received:
                    base.print_success("IP address pool is exhausted: ", 
                                       str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
                else:
                    base.print_error("DHCP Starvation failed timeout!")
                sleep(1)
                exit(1)
            sleep(int(args.delay))
    
    except KeyboardInterrupt:
        base.print_info("Exit")
        discover_raw_socket.close()
        exit(0)
# endregion


# region Send DHCP request 
Example #13
Source File: send_tcp_packets.py    From raw-packet with MIT License 5 votes vote down vote up
def arp_reply(your_mac_address, your_ip_address, target_mac_address, target_ip_address):
    SOCK = socket(AF_PACKET, SOCK_RAW)
    SOCK.bind((current_network_interface, 0))
    arp_reply = arp.make_response(ethernet_src_mac=your_mac_address,
                                  ethernet_dst_mac=target_mac_address,
                                  sender_mac=your_mac_address, sender_ip=your_ip_address,
                                  target_mac=target_mac_address, target_ip=target_ip_address)
    SOCK.send(arp_reply)
    SOCK.close() 
Example #14
Source File: send_tcp_packets.py    From raw-packet with MIT License 5 votes vote down vote up
def sender():
    sleep(5)

    SOCK = socket(AF_PACKET, SOCK_RAW)
    SOCK.bind((current_network_interface, 0))

    sequence = randint(1, 1000000)

    syn_header = tcp.make_syn_header(src_ip_address, dst_ip_address, src_port, dst_port, sequence)
    ip_header = ip.make_header(src_ip_address, dst_ip_address, 0, len(syn_header), 6)
    eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
    syn_packet = eth_header + ip_header + syn_header

    SOCK.send(syn_packet)

    while True:
        if response_sequence_number == 0:
            sleep(1)
        else:
            if response_acknowledgement_number == sequence + 1:
                break
            else:
                sleep(1)

    sequence += 1
    acknowledgment = response_sequence_number + 1
    ack_header = tcp.make_ack_header(src_ip_address, dst_ip_address, src_port, dst_port,
                                     sequence, acknowledgment, response_timestamp)
    ip_header = ip.make_header(src_ip_address, dst_ip_address, 0, len(ack_header), 6)
    eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
    ack_packet = eth_header + ip_header + ack_header
    SOCK.send(ack_packet)

    psh_header = tcp.make_psh_header(src_ip_address, dst_ip_address, src_port, dst_port,
                                     sequence, acknowledgment, response_timestamp, data)
    ip_header = ip.make_header(src_ip_address, dst_ip_address, len(data), len(psh_header), 6)
    eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
    psh_packet = eth_header + ip_header + psh_header + data
    SOCK.send(psh_packet)

    SOCK.close() 
Example #15
Source File: probe.py    From Nscan with Apache License 2.0 5 votes vote down vote up
def send(self, hosts, srcp, gen):
		if 'ppp' in self.ifname:
			family = socket.AF_INET
			proto = socket.IPPROTO_RAW
			eth = ''
		else:
			family = socket.AF_PACKET
			proto = ETH_P_IP
			eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()
		sock = socket.socket(family, socket.SOCK_RAW, proto)
		transport = self.__Transport(srcp, 0)
		npacket = 0
		self.events['send'].wait()
		target = hosts[0]
		while self.events['send'].isSet():
			try:
				target = hosts[0] + gen.next()
				iph = ip.IP(self.diface, dec2dot(target), self.stype)
			except StopIteration:
				break
			for port_list in self.ports:
				for port in range(port_list[0], port_list[1]):
					if self.events['send'].isSet():
						transport.dstp = port
						packet = eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst)
						sock.sendto(packet, (dec2dot(target), 0)) # self.ifname
						npacket+=1
						if not npacket%self.cooldown[0]:
							time.sleep(self.cooldown[1])
					else:
						break
		logging.info('[SEND] Sent: {} packets'.format(npacket))
		sock.close() 
Example #16
Source File: sockets.py    From Doga with MIT License 5 votes vote down vote up
def create_raw_socket(self):
        """ Create row socket(SOCK_RAW type) to listen for traffic
        """

        try:
            self.raw_socket = socket.socket(
                socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
        except socket.error, msg:
            print "unable to create socket"
            print "Error Code %d : Message %s" % (msg[0], msg[1])
            sys.exit() 
Example #17
Source File: test_nl_send_simple.py    From libnl with GNU Lesser General Public License v2.1 4 votes vote down vote up
def test_dissect(monkeypatch):
    r"""Diff of C code (from test_bare()) to test against.

    --- test_bare.c	2015-02-08 12:43:15.543135855 -0800
    +++ test_dissect.c	2015-02-08 13:25:31.375715668 -0800
    @@ -16,8 +16,22 @@
             sk->s_local.nl_pid = 0;
             sk->s_seq_next = 0;

    -        int ret = nl_send_simple(sk, RTM_GETLINK, 0, NULL, 0);
    +        struct rtgenmsg rt_hdr = { .rtgen_family = AF_PACKET, };
    +        struct nl_msg *msg = nlmsg_alloc_simple(RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP);
    +        nlmsg_append(msg, &rt_hdr, sizeof(rt_hdr), NLMSG_ALIGNTO);
    +        nl_complete_msg(sk, msg);
    +        struct nlmsghdr *nlh = nlmsg_hdr(msg);

    +        printf("%d == nlh->nlmsg_len\n", nlh->nlmsg_len);
    +        printf("%d == nlh->nlmsg_type\n", nlh->nlmsg_type);
    +        printf("%d == nlh->nlmsg_flags\n", nlh->nlmsg_flags);
    +        printf("%d == nlh->nlmsg_seq\n", nlh->nlmsg_seq);
    +        printf("%d == nlh->nlmsg_pid\n", nlh->nlmsg_pid);
    +
    +        struct iovec iov = { .iov_base = nlh, .iov_len = nlh->nlmsg_len };
    +        struct msghdr hdr = { .msg_iov = &iov, .msg_iovlen = 1, };
    +
    +        int ret = nl_sendmsg(sk, msg, &hdr);
             printf("Bytes: %d\n", ret);
             return 0;
         }
    """
    monkeypatch.setattr(libnl.socket_, 'generate_local_port', lambda: 0)

    sk = nl_socket_alloc()
    nl_connect(sk, NETLINK_ROUTE)
    sk.socket_instance.close()
    sk.s_local.nl_pid = 0
    sk.s_seq_next = 0

    rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)
    msg = nlmsg_alloc_simple(RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP)
    nlmsg_append(msg, rt_hdr, rt_hdr.SIZEOF, NLMSG_ALIGNTO)
    nl_complete_msg(sk, msg)
    nlh = nlmsg_hdr(msg)

    assert 20 == nlh.nlmsg_len
    assert 18 == nlh.nlmsg_type
    assert 773 == nlh.nlmsg_flags
    assert 0 == nlh.nlmsg_seq
    assert 0 == nlh.nlmsg_pid

    assert b'FAAAABIABQMAAAAAAAAAABEAAAA=' == base64.b64encode(buffer(nlh.bytearray[:nlh.nlmsg_len]))
    nl_socket_free(sk) 
Example #18
Source File: ifaddrs.py    From BitTorrent with GNU General Public License v3.0 4 votes vote down vote up
def sockaddr2addr(ifname, addr):
    """
    Convert a sockaddr pointer (addr) to a descriptive dict or None
    for a void pointer.
    """
    if addr:
        sa = addr[0]
    else:
        return None
    d = { 'family': addrfamily(sa.sa_family) }
    if hasattr(socket, 'AF_INET6') and sa.sa_family == socket.AF_INET6:
        sin6 = cast(addr, POINTER(sockaddr_in6))[0]
        d['port'] = sin6.sin6_port or None
        d['addr'] = ':'.join([ '%04.4x' % socket.ntohs(x) for x in sin6.sin6_addr.in6_u.u6_addr16 ])
        d['flowinfo'] = sin6.sin6_flowinfo or None
        d['scope_id'] = sin6.sin6_scope_id
    elif hasattr(socket, 'AF_INET') and sa.sa_family == socket.AF_INET:
        sin = cast(addr, POINTER(sockaddr_in))[0]
        d['port'] = sin.sin_port or None
        d['addr'] = '.'.join([ str(ord(x)) for x in struct.pack('I', sin.sin_addr.s_addr) ])
    elif hasattr(socket, 'AF_PACKET') and sa.sa_family == socket.AF_PACKET:
        sll = cast(addr, POINTER(sockaddr_ll))[0]
        #d['ifindex'] = sll.sll_ifindex
        hwaddr = None
        if sll.sll_hatype == ARPHRD_ETHER and sll.sll_halen == 6:
            hwaddr = ':'.join([ chr(x).encode('hex') for x in sll.sll_addr[:sll.sll_halen] ])
        elif sll.sll_hatype == ARPHRD_SIT and sll.sll_halen == 4:
            try:
                hwaddr = socket.inet_ntop(socket.AF_INET,
                                          ''.join([ chr(x) for x in sll.sll_addr[:sll.sll_halen] ]))
            except:
                pass
        d['addr'] = (ifname,
                     eth_protocol_type(sll.sll_protocol),
                     packet_type(sll.sll_pkttype),
                     hardware_type(sll.sll_hatype),
                     ) + ((hwaddr is not None) and (hwaddr,) or ())
    else:
        pass
    try:
        if 'addr' in d:
            d['addr'] = socket.inet_ntop(sa.sa_family,
                                         socket.inet_pton(sa.sa_family,
                                                          d['addr']))
    except:
        pass
    return dict([ (k, v) for k, v in d.items() if v is not None ]) 
Example #19
Source File: ifaddrs.py    From BitTorrent with GNU General Public License v3.0 4 votes vote down vote up
def sockaddr2addr(ifname, addr):
    """
    Convert a sockaddr pointer (addr) to a descriptive dict or None
    for a void pointer.
    """
    if addr:
        sa = addr[0]
    else:
        return None
    d = { 'family': addrfamily(sa.sa_family) }
    if hasattr(socket, 'AF_INET6') and sa.sa_family == socket.AF_INET6:
        sin6 = cast(addr, POINTER(sockaddr_in6))[0]
        d['port'] = sin6.sin6_port or None
        d['addr'] = ':'.join([ '%04.4x' % socket.ntohs(x) for x in sin6.sin6_addr.in6_u.u6_addr16 ])
        d['flowinfo'] = sin6.sin6_flowinfo or None
        d['scope_id'] = sin6.sin6_scope_id
    elif hasattr(socket, 'AF_INET') and sa.sa_family == socket.AF_INET:
        sin = cast(addr, POINTER(sockaddr_in))[0]
        d['port'] = sin.sin_port or None
        d['addr'] = '.'.join([ str(ord(x)) for x in struct.pack('I', sin.sin_addr.s_addr) ])
    elif hasattr(socket, 'AF_PACKET') and sa.sa_family == socket.AF_PACKET:
        sll = cast(addr, POINTER(sockaddr_ll))[0]
        #d['ifindex'] = sll.sll_ifindex
        hwaddr = None
        if sll.sll_hatype == ARPHRD_ETHER and sll.sll_halen == 6:
            hwaddr = ':'.join([ chr(x).encode('hex') for x in sll.sll_addr[:sll.sll_halen] ])
        elif sll.sll_hatype == ARPHRD_SIT and sll.sll_halen == 4:
            try:
                hwaddr = socket.inet_ntop(socket.AF_INET,
                                          ''.join([ chr(x) for x in sll.sll_addr[:sll.sll_halen] ]))
            except:
                pass
        d['addr'] = (ifname,
                     eth_protocol_type(sll.sll_protocol),
                     packet_type(sll.sll_pkttype),
                     hardware_type(sll.sll_hatype),
                     ) + ((hwaddr is not None) and (hwaddr,) or ())
    else:
        pass
    try:
        if 'addr' in d:
            d['addr'] = socket.inet_ntop(sa.sa_family,
                                         socket.inet_pton(sa.sa_family,
                                                          d['addr']))
    except:
        pass
    return dict([ (k, v) for k, v in d.items() if v is not None ]) 
Example #20
Source File: test_system.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
def test_net_if_addrs(self):
        nics = psutil.net_if_addrs()
        assert nics, nics

        nic_stats = psutil.net_if_stats()

        # Not reliable on all platforms (net_if_addrs() reports more
        # interfaces).
        # self.assertEqual(sorted(nics.keys()),
        #                  sorted(psutil.net_io_counters(pernic=True).keys()))

        families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, str)
            self.assertEqual(len(set(addrs)), len(addrs))
            for addr in addrs:
                self.assertIsInstance(addr.family, int)
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None)))
                self.assertIn(addr.family, families)
                if sys.version_info >= (3, 4):
                    self.assertIsInstance(addr.family, enum.IntEnum)
                if nic_stats[nic].isup:
                    # Do not test binding to addresses of interfaces
                    # that are down
                    if addr.family == socket.AF_INET:
                        s = socket.socket(addr.family)
                        with contextlib.closing(s):
                            s.bind((addr.address, 0))
                    elif addr.family == socket.AF_INET6:
                        info = socket.getaddrinfo(
                            addr.address, 0, socket.AF_INET6,
                            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
                        af, socktype, proto, canonname, sa = info
                        s = socket.socket(af, socktype, proto)
                        with contextlib.closing(s):
                            s.bind(sa)
                for ip in (addr.address, addr.netmask, addr.broadcast,
                           addr.ptp):
                    if ip is not None:
                        # TODO: skip AF_INET6 for now because I get:
                        # AddressValueError: Only hex digits permitted in
                        # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
                        if addr.family != socket.AF_INET6:
                            check_net_address(ip, addr.family)
                # broadcast and ptp addresses are mutually exclusive
                if addr.broadcast:
                    self.assertIsNone(addr.ptp)
                elif addr.ptp:
                    self.assertIsNone(addr.broadcast)

        if BSD or OSX or SUNOS:
            if hasattr(socket, "AF_LINK"):
                self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
        elif LINUX:
            self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
        elif WINDOWS:
            self.assertEqual(psutil.AF_LINK, -1) 
Example #21
Source File: test_system.py    From psutil with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_net_if_addrs(self):
        nics = psutil.net_if_addrs()
        assert nics, nics

        nic_stats = psutil.net_if_stats()

        # Not reliable on all platforms (net_if_addrs() reports more
        # interfaces).
        # self.assertEqual(sorted(nics.keys()),
        #                  sorted(psutil.net_io_counters(pernic=True).keys()))

        families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, str)
            self.assertEqual(len(set(addrs)), len(addrs))
            for addr in addrs:
                self.assertIsInstance(addr.family, int)
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None)))
                self.assertIn(addr.family, families)
                if sys.version_info >= (3, 4) and not PYPY:
                    self.assertIsInstance(addr.family, enum.IntEnum)
                if nic_stats[nic].isup:
                    # Do not test binding to addresses of interfaces
                    # that are down
                    if addr.family == socket.AF_INET:
                        s = socket.socket(addr.family)
                        with contextlib.closing(s):
                            s.bind((addr.address, 0))
                    elif addr.family == socket.AF_INET6:
                        info = socket.getaddrinfo(
                            addr.address, 0, socket.AF_INET6,
                            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
                        af, socktype, proto, canonname, sa = info
                        s = socket.socket(af, socktype, proto)
                        with contextlib.closing(s):
                            s.bind(sa)
                for ip in (addr.address, addr.netmask, addr.broadcast,
                           addr.ptp):
                    if ip is not None:
                        # TODO: skip AF_INET6 for now because I get:
                        # AddressValueError: Only hex digits permitted in
                        # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
                        if addr.family != socket.AF_INET6:
                            check_net_address(ip, addr.family)
                # broadcast and ptp addresses are mutually exclusive
                if addr.broadcast:
                    self.assertIsNone(addr.ptp)
                elif addr.ptp:
                    self.assertIsNone(addr.broadcast)

        if BSD or MACOS or SUNOS:
            if hasattr(socket, "AF_LINK"):
                self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
        elif LINUX:
            self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
        elif WINDOWS:
            self.assertEqual(psutil.AF_LINK, -1) 
Example #22
Source File: test_system.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def test_net_if_addrs(self):
        nics = psutil.net_if_addrs()
        assert nics, nics

        nic_stats = psutil.net_if_stats()

        # Not reliable on all platforms (net_if_addrs() reports more
        # interfaces).
        # self.assertEqual(sorted(nics.keys()),
        #                  sorted(psutil.net_io_counters(pernic=True).keys()))

        families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, str)
            self.assertEqual(len(set(addrs)), len(addrs))
            for addr in addrs:
                self.assertIsInstance(addr.family, int)
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None)))
                self.assertIn(addr.family, families)
                if sys.version_info >= (3, 4):
                    self.assertIsInstance(addr.family, enum.IntEnum)
                if nic_stats[nic].isup:
                    # Do not test binding to addresses of interfaces
                    # that are down
                    if addr.family == socket.AF_INET:
                        s = socket.socket(addr.family)
                        with contextlib.closing(s):
                            s.bind((addr.address, 0))
                    elif addr.family == socket.AF_INET6:
                        info = socket.getaddrinfo(
                            addr.address, 0, socket.AF_INET6,
                            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
                        af, socktype, proto, canonname, sa = info
                        s = socket.socket(af, socktype, proto)
                        with contextlib.closing(s):
                            s.bind(sa)
                for ip in (addr.address, addr.netmask, addr.broadcast,
                           addr.ptp):
                    if ip is not None:
                        # TODO: skip AF_INET6 for now because I get:
                        # AddressValueError: Only hex digits permitted in
                        # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
                        if addr.family != socket.AF_INET6:
                            check_net_address(ip, addr.family)
                # broadcast and ptp addresses are mutually exclusive
                if addr.broadcast:
                    self.assertIsNone(addr.ptp)
                elif addr.ptp:
                    self.assertIsNone(addr.broadcast)

        if BSD or OSX or SUNOS:
            if hasattr(socket, "AF_LINK"):
                self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
        elif LINUX:
            self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
        elif WINDOWS:
            self.assertEqual(psutil.AF_LINK, -1)