Python socket.AF_PACKET() Examples

The following are code examples for showing how to use socket.AF_PACKET(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: raw-packet   Author: raw-packet   File: arp_scanner.py    MIT License 7 votes vote down vote up
def __init__(self):
        self.base = Base()
        self.eth = Ethernet_raw()
        self.arp = ARP_raw()
        self.rawSocket = socket(AF_PACKET, SOCK_RAW, htons(0x0003))
        self.results = []
        self.unique_results = []
        self.mac_addresses = []

        self.mac_prefixes_file = "mac-prefixes.txt"
        self.vendor_list = []

        self.retry_number = 3
        self.timeout = 0
    # endregion

    # region Sniffer 
Example 2
Project: raw-packet   Author: raw-packet   File: icmpv6_scanner.py    MIT License 6 votes vote down vote up
def __init__(self):
        self.base = Base()
        self.eth = Ethernet_raw()
        self.ipv6 = IPv6_raw()
        self.icmpv6 = ICMPv6_raw()

        self.rawSocket = socket(AF_PACKET, SOCK_RAW, htons(0x0003))

        self.results = []
        self.unique_results = []
        self.mac_addresses = []

        self.retry_number = 3
        self.timeout = 0

        self.router_info = {}

        # region Create vendor list
        self.vendor_list = self.base.get_mac_prefixes()
        # endregion

    # endregion

    # region Sniffer 
Example 3
Project: raw-packet   Author: raw-packet   File: dhcpv6_rogue_server.py    MIT License 6 votes vote down vote up
def send_icmpv6_solicit_packets():
    icmpv6_solicit_raw_socket = socket(AF_PACKET, SOCK_RAW)
    icmpv6_solicit_raw_socket.bind((current_network_interface, 0))

    try:
        while True:
            icmpv6_solicit_packet = icmpv6.make_router_solicit_packet(ethernet_src_mac=your_mac_address,
                                                                      ipv6_src=your_local_ipv6_address,
                                                                      need_source_link_layer_address=True,
                                                                      source_link_layer_address=eth.get_random_mac())
            icmpv6_solicit_raw_socket.send(icmpv6_solicit_packet)
            sleep(int(args.delay))

    except KeyboardInterrupt:
        Base.print_info("Exit")
        icmpv6_solicit_raw_socket.close()
        exit(0)
# endregion


# region Send DHCPv6 solicit packets 
Example 4
Project: raw-packet   Author: raw-packet   File: dhcpv6_rogue_server.py    MIT License 6 votes vote down vote up
def send_dhcpv6_solicit_packets():
    dhcpv6_solicit_raw_socket = socket(AF_PACKET, SOCK_RAW)
    dhcpv6_solicit_raw_socket.bind((current_network_interface, 0))

    try:
        while True:
            Client_DUID = dhcpv6.get_duid(eth.get_random_mac())
            request_options = [23, 24]

            dhcpv6_solicit_packet = dhcpv6.make_solicit_packet(ethernet_src_mac=your_mac_address,
                                                               ipv6_src=your_local_ipv6_address,
                                                               transaction_id=randint(1, 16777215),
                                                               client_identifier=Client_DUID,
                                                               option_request_list=request_options)
            dhcpv6_solicit_raw_socket.send(dhcpv6_solicit_packet)
            sleep(int(args.delay))

    except KeyboardInterrupt:
        Base.print_info("Exit")
        dhcpv6_solicit_raw_socket.close()
        exit(0)
# endregion


# region Send ICMPv6 advertise packets 
Example 5
Project: raw-packet   Author: raw-packet   File: dhcp_rogue_server.py    MIT License 6 votes vote down vote up
def make_dhcp_nak_packet(transaction_id,  target_mac, target_ip, requested_ip):
    return dhcp.make_nak_packet(source_mac=dhcp_server_mac_address,
                                destination_mac=target_mac,
                                source_ip=dhcp_server_ip_address,
                                destination_ip=requested_ip,
                                transaction_id=transaction_id,
                                your_ip=target_ip,
                                client_mac=target_mac,
                                dhcp_server_id=dhcp_server_ip_address)
# endregion

# def ack_sender():
#     SOCK = socket(AF_PACKET, SOCK_RAW)
#     SOCK.bind((current_network_interface, 0))
#     ack_packet = make_dhcp_ack_packet(transaction_id_global, requested_ip_address)
#     while True:
#         SOCK.send(ack_packet)
#         sleep(0.01)


# region Send DHCP discover packets 
Example 6
Project: raw-packet   Author: raw-packet   File: apple_rogue_dhcp.py    MIT License 6 votes vote down vote up
def dhcp_response_sender():
    SOCK = socket(AF_PACKET, SOCK_RAW)
    SOCK.bind((current_network_interface, 0))

    offer_packet = make_dhcp_offer_packet(transaction_id_global)
    ack_packet = make_dhcp_ack_packet(transaction_id_global)

    while True:
        discover_packet = dhcp.make_discover_packet(ethernet_src_mac=your_mac_address,
                                                    client_mac=eth.get_random_mac(),
                                                    host_name=Base.make_random_string(6))
        SOCK.send(discover_packet)
        SOCK.send(offer_packet)
        SOCK.send(ack_packet)
        sleep(0.05)
# endregion


# region Reply to DHCP and ARP requests 
Example 7
Project: raw-packet   Author: raw-packet   File: dnsmasploit.py    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 8
Project: vrnetlab   Author: plajjan   File: xcon.py    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 9
Project: libnl   Author: Robpol86   File: example_list_network_interfaces.py    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 10
Project: deb-ryu   Author: openstack   File: sample_router.py    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
Project: Nscan   Author: OffensivePython   File: probe.py    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 12
Project: raw-packet   Author: raw-packet   File: dns_server.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.base = Base()
        self.sniff = Sniff_raw()
        self.dns = DNS_raw()

        self.rawSocket = socket(AF_PACKET, SOCK_RAW)

        self.port = 53
        self.A_DNS_QUERY = 1
        self.AAAA_DNS_QUERY = 28
    # endregion

    # region Get first IPv4 or IPv6 address of domain 
Example 13
Project: raw-packet   Author: raw-packet   File: send_tcp_packets.py    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 14
Project: raw-packet   Author: raw-packet   File: send_tcp_packets.py    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 15
Project: raw-packet   Author: raw-packet   File: dhcpv6_rogue_server.py    MIT License 5 votes vote down vote up
def send_icmpv6_advertise_packets():
    icmpv6_advertise_raw_socket = socket(AF_PACKET, SOCK_RAW)
    icmpv6_advertise_raw_socket.bind((current_network_interface, 0))

    icmpv6_ra_packet = icmpv6.make_router_advertisement_packet(ethernet_src_mac=your_mac_address,
                                                               ethernet_dst_mac="33:33:00:00:00:01",
                                                               ipv6_src=your_local_ipv6_address,
                                                               ipv6_dst="ff02::1",
                                                               dns_address=recursive_dns_address,
                                                               domain_search=dns_search,
                                                               prefix=network_prefix,
                                                               router_lifetime=5000,
                                                               advertisement_interval=int(args.delay) * 1000)
    try:
        while True:
            icmpv6_advertise_raw_socket.send(icmpv6_ra_packet)
            sleep(int(args.delay))

    except KeyboardInterrupt:
        Base.print_info("Exit")
        icmpv6_advertise_raw_socket.close()
        exit(0)


# endregion


# region Reply to DHCPv6 and ICMPv6 requests 
Example 16
Project: raw-packet   Author: raw-packet   File: dhcp_rogue_server.py    MIT License 5 votes vote down vote up
def discover_sender(number_of_packets=999999):
    global discover_sender_is_work
    discover_sender_is_work = True

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

    if dhcp_discover_packets_source_mac != your_mac_address:
        relay_agent_ip_address = Base.get_netiface_random_ip(current_network_interface)
        while packet_index < number_of_packets:
            try:
                discover_packet = dhcp.make_discover_packet(source_mac=dhcp_discover_packets_source_mac,
                                                            client_mac=eth.get_random_mac(),
                                                            host_name=Base.make_random_string(8),
                                                            relay_ip=relay_agent_ip_address)
                SOCK.send(discover_packet)
                sleep(args.discover_delay)
            except:
                Base.print_error("Something went wrong when sending DHCP discover packets!")
            packet_index += 1

    else:
        while packet_index < number_of_packets:
            try:
                discover_packet = dhcp.make_discover_packet(source_mac=dhcp_discover_packets_source_mac,
                                                            client_mac=eth.get_random_mac(),
                                                            host_name=Base.make_random_string(8),
                                                            relay_ip=your_ip_address)
                SOCK.send(discover_packet)
                sleep(args.discover_delay)
            except:
                Base.print_error("Something went wrong when sending DHCP discover packets!")
            packet_index += 1

    SOCK.close()
    discover_sender_is_work = False
# endregion


# region Reply to DHCP and ARP requests 
Example 17
Project: dash-listeners   Author: DanGe42   File: arp_listener.py    MIT License 5 votes vote down vote up
def create(cls):
        raw_socket = socket.socket(
            socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) # pylint: disable=E1101
        return cls(raw_socket) 
Example 18
Project: emulated-sdn-application   Author: tranlyvu   File: sample_router.py    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 19
Project: empower-ryu   Author: clicknf   File: sample_router.py    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 20
Project: ryu-lagopus-ext   Author: lagopus   File: sample_router.py    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 21
Project: happy   Author: openweave   File: HappyPacketProcess.py    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 22
Project: Ryu-Qos   Author: xiaobinglu   File: sample_router.py    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 23
Project: SDN-QoS-Routing   Author: dodoyuan   File: sample_router.py    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 24
Project: libnl   Author: Robpol86   File: test_nl_send_simple.py    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 25
Project: vnpy_crypto   Author: birforce   File: test_system.py    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) 
Example 26
Project: teleport   Author: tp4a   File: test_system.py    Apache License 2.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 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 27
Project: deskOrg   Author: saleguas   File: test_system.py    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 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 28
Project: FancyWord   Author: EastonLee   File: test_system.py    GNU General Public License v3.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, AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, (str, unicode))
            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 != 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 29
Project: ProcessFS   Author: mherrmann   File: test_system.py    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) 
Example 30
Project: BL-Bot   Author: IOIIIO   File: test_system.py    GNU General Public License v3.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 31
Project: libtorrent   Author: galaxy001   File: ifaddrs.py    MIT License 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 32
Project: libnl   Author: Robpol86   File: test_nl_send_simple.py    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 33
Project: my_hass_config   Author: ivencooli   File: test_system.py    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, AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, (str, unicode))
            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 != 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)