Python socket.htons() Examples

The following are 30 code examples for showing how to use socket.htons(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: vulscan   Author: vulscanteam   File: packet.py    License: MIT License 6 votes vote down vote up
def __init__(self, srcp, dstp, seqn=1):
        self.srcp = srcp
        self.dstp = dstp
        self.seqn = seqn
        self.ackn = 0
        self.offset = 5  # Data offset: 5x4 = 20 bytes
        self.reserved = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 1
        self.fin = 0
        self.window = socket.htons(5840)
        self.checksum = 0
        self.urgp = 0
        self.payload = "" 
Example 2
Project: Nscan   Author: OffensivePython   File: tcp.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, srcp, dstp):
        self.srcp = srcp
        self.dstp = dstp
        self.seqn = 10
        self.ackn = 0
        self.offset = 5 # Data offset: 5x4 = 20 bytes
        self.reserved = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 1
        self.fin = 0
        self.window = htons(5840)
        self.checksum = 0
        self.urgp = 0
        self.payload = "" 
Example 3
Project: Nscan   Author: OffensivePython   File: ip.py    License: Apache License 2.0 6 votes vote down vote up
def pack(self):
        ip_header = struct.pack("!BBHHHBBH4s4s",
                    self.ver_ihl,
                    self.tos,
                    self.length,
                    self.id,
                    self.flags_offset,
                    self.ttl,
                    self.protocol,
                    0, # checksum should be 0
                    self.src,
                    self.dst)
        self.checksum = checksum(ip_header)
        ip_header = struct.pack("!BBHHHBBH4s4s",
                    self.ver_ihl,
                    self.tos,
                    self.length,
                    self.id,
                    self.flags_offset,
                    self.ttl,
                    self.protocol,
                    socket.htons(self.checksum),
                    self.src,
                    self.dst)
        return ip_header 
Example 4
Project: Nscan   Author: OffensivePython   File: tcp.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, srcp, dstp):
        self.srcp = srcp
        self.dstp = dstp
        self.seqn = 10
        self.ackn = 0
        self.offset = 5 # Data offset: 5x4 = 20 bytes
        self.reserved = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 1
        self.fin = 0
        self.window = htons(5840)
        self.checksum = 0
        self.urgp = 0
        self.payload = "" 
Example 5
Project: g3ar   Author: VillanCh   File: ping.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 6
Project: g3ar   Author: VillanCh   File: ping.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 7
Project: AIT-Core   Author: NASA-AMMOS   File: test_bsc.py    License: MIT License 6 votes vote down vote up
def test_mocked_eth_socket(self, socket_mock):
        socket_family = getattr(gevent.socket,
                                'AF_PACKET',
                                gevent.socket.AF_INET)
        proto = bsc.ETH_PROTOCOL
        handler = {'name':'name', 'log_dir':'/tmp'}
        bsc.RAW_SOCKET_FD = 'foobar'
        sl = bsc.SocketStreamCapturer([handler], ['eho0', 0], 'ethernet')
        # We need to test a different load if the rawsocket package is used
        if not bsc.RAW_SOCKET_FD:
            socket_mock.socket.assert_called_with(socket_family,
                                                  gevent.socket.SOCK_RAW,
                                                  socket.htons(proto))
        else:
            socket_mock.fromfd.assert_called_with(bsc.RAW_SOCKET_FD,
                                                  socket_family,
                                                  gevent.socket.SOCK_RAW,
                                                  socket.htons(proto))
        assert sl.conn_type == 'ethernet'
        bsc.RAW_SOCKET_FD = None 
Example 8
Project: AIT-Core   Author: NASA-AMMOS   File: test_bsc.py    License: MIT License 6 votes vote down vote up
def test_mocked_eth_socket_with_rawsocket(self, socket_mock):
        socket_family = getattr(gevent.socket,
                                'AF_PACKET',
                                gevent.socket.AF_INET)

        rawsocket_is_installed = True if bsc.RAW_SOCKET_FD else False
        if not rawsocket_is_installed:
            rawsocket_fd = 'fake_rawsocket_fd'
            bsc.RAW_SOCKET_FD = rawsocket_fd
        else:
            rawsocket_fd = bsc.RAW_SOCKET_FD

        handler = {'name':'name', 'log_dir':'/tmp'}
        sl = bsc.SocketStreamCapturer([handler], ['eho0', 0], 'ethernet')
        # We need to test a different load if the rawsocket package is used
        socket_mock.fromfd.assert_called_with(rawsocket_fd,
                                              socket_family,
                                              gevent.socket.SOCK_RAW,
                                              socket.htons(bsc.ETH_PROTOCOL))
        assert sl.conn_type == 'ethernet'

        if not rawsocket_is_installed:
            bsc.RAW_SOCKET_FD = None 
Example 9
Project: scapy   Author: secdev   File: supersocket.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, type=ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):  # noqa: E501
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)  # noqa: E501
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))  # noqa: E501
        self.iface = iface
        if iface is not None:
            self.ins.bind((self.iface, type))
        if not six.PY2:
            try:
                # Receive Auxiliary Data (VLAN tags)
                self.ins.setsockopt(SOL_PACKET, PACKET_AUXDATA, 1)
                self.ins.setsockopt(
                    socket.SOL_SOCKET,
                    SO_TIMESTAMPNS,
                    1
                )
                self.auxdata_available = True
            except OSError:
                # Note: Auxiliary Data is only supported since
                #       Linux 2.6.21
                msg = "Your Linux Kernel does not support Auxiliary Data!"
                log_runtime.info(msg) 
Example 10
Project: scapy   Author: secdev   File: inet.py    License: GNU General Public License v2.0 6 votes vote down vote up
def answers(self, other):
        if not isinstance(other, IP):
            return 0

        # Check if IP addresses match
        test_IPsrc = not conf.checkIPsrc or self.src == other.src
        test_IPdst = self.dst == other.dst

        # Check if IP ids match
        test_IPid = not conf.checkIPID or self.id == other.id
        test_IPid |= conf.checkIPID and self.id == socket.htons(other.id)

        # Check if IP protocols match
        test_IPproto = self.proto == other.proto

        if not (test_IPsrc and test_IPdst and test_IPid and test_IPproto):
            return 0

        return self.payload.answers(other.payload) 
Example 11
Project: stash   Author: ywangd   File: ping.py    License: MIT License 6 votes vote down vote up
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr = socket.gethostbyname(dest_addr)

    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0

    # Make a dummy heder with a 0 checksum.
    header = struct.pack(b"bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * b"Q"
    data = struct.pack("d", default_timer()) + data

    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)

    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(b"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1)
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1))  # Don't know about the 1 
Example 12
Project: ryu   Author: OpenState-SDN   File: monitor_linux.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(VRRPInterfaceMonitorNetworkDevice, self).__init__(*args,
                                                                **kwargs)
        self.__is_active = True
        config = self.config
        if config.is_ipv6:
            family = socket.AF_INET6
            ether_type = ether.ETH_TYPE_IPV6
            mac_address = vrrp.vrrp_ipv6_src_mac_address(config.vrid)
        else:
            family = socket.AF_INET
            ether_type = ether.ETH_TYPE_IP
            mac_address = vrrp.vrrp_ipv4_src_mac_address(config.vrid)
        # socket module doesn't define IPPROTO_VRRP
        self.ip_socket = socket.socket(family, socket.SOCK_RAW,
                                       inet.IPPROTO_VRRP)

        self.packet_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                                           socket.htons(ether_type))
        self.packet_socket.bind((self.interface.device_name, ether_type,
                                 socket.PACKET_MULTICAST,
                                 arp.ARP_HW_TYPE_ETHERNET,
                                 addrconv.mac.text_to_bin(mac_address)))

        self.ifindex = if_nametoindex(self.interface.device_name) 
Example 13
Project: PythonMiniProbe   Author: PRTG   File: nmap.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_one_ping(self, my_socket, dest_addr, ID):
        """
        Send one ping to the given >dest_addr<.
        """
        dest_addr  =  socket.gethostbyname(dest_addr)
        # Header is type (8), code (8), checksum (16), id (16), sequence (16)
        my_checksum = 0
        # Make a dummy heder with a 0 checksum.
        header = struct.pack("bbHHh", self.ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
        bytesInDouble = struct.calcsize("d")
        data = (192 - bytesInDouble) * "Q"
        data = struct.pack("d", time.time()) + data
        # Calculate the checksum on the data and the dummy header.
        my_checksum = self.checksum(header + data)
        # Now that we have the right checksum, we put that in. It's just easier
        # to make up a new header than to stuff it into the dummy.
        header = struct.pack(
            "bbHHh", self.ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
        )
        packet = header + data
        my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 
Example 14
Project: vulscan   Author: vulscanteam   File: packet.py    License: MIT License 5 votes vote down vote up
def recv(event, src, dst, srcp, dstp, buff, timeout):
    """
        event: should be set when a packet is sent
        src: source ip
        dst: destination ip
        srcp: source port
        dstp: destination port
        buff: buffer for received data
    """
    sock = socket.socket(socket.AF_PACKET,
                         socket.SOCK_DGRAM,
                         socket.htons(ETH_P_IP))
    sock.settimeout(timeout)
    event.wait()

    while True:
        try:
            data, sa_ll = sock.recvfrom(65535)
            if sa_ll[1] == ETH_P_IP and sa_ll[2] == socket.PACKET_HOST:
                break  # break if we captured incoming ip packet,
        except socket.timeout as e:
            print 'socket.timeout:', e
            sock.close()
            return
        except socket.error as e:
            print 'socket.error:', e
            sock.close()
            return
    sip = data[12:16]  # src ip
    dip = data[16:20]  # dst ip
    sp = data[20:22]  # src port
    dp = data[22:24]  # dst port

    if (sip == dst and dip == src and sp == dstp and dp == srcp):
        buff.append(data)  # return received packet
        event.clear()
    sock.close() 
Example 15
Project: vulscan   Author: vulscanteam   File: packet.py    License: MIT License 5 votes vote down vote up
def pack(self):
        ver_ihl = (self.version << 4) + self.ihl
        flags_offset = (self.flags << 13) + self.offset
        ip_header = struct.pack("!BBHHHBBH4s4s",
                                ver_ihl,
                                self.tos,
                                self.tl,
                                self.id,
                                flags_offset,
                                self.ttl,
                                self.protocol,
                                self.checksum,
                                self.source,
                                self.destination)
        self.checksum = checksum(ip_header)
        ip_header = struct.pack("!BBHHHBBH4s4s",
                                ver_ihl,
                                self.tos,
                                self.tl,
                                self.id,
                                flags_offset,
                                self.ttl,
                                self.protocol,
                                socket.htons(self.checksum),
                                self.source,
                                self.destination)
        return ip_header 
Example 16
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testNtoH(self):
        # This just checks that htons etc. are their own inverse,
        # when looking at the lower 16 or 32 bits.
        sizes = {socket.htonl: 32, socket.ntohl: 32,
                 socket.htons: 16, socket.ntohs: 16}
        for func, size in sizes.items():
            mask = (1L<<size) - 1
            for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
                self.assertEqual(i & mask, func(func(i&mask)) & mask)

            swapped = func(mask)
            self.assertEqual(swapped & mask, mask)
            self.assertRaises(OverflowError, func, 1L<<34) 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testNtoHErrors(self):
        good_values = [ 1, 2, 3, 1L, 2L, 3L ]
        bad_values = [ -1, -2, -3, -1L, -2L, -3L ]
        for k in good_values:
            socket.ntohl(k)
            socket.ntohs(k)
            socket.htonl(k)
            socket.htons(k)
        for k in bad_values:
            self.assertRaises(OverflowError, socket.ntohl, k)
            self.assertRaises(OverflowError, socket.ntohs, k)
            self.assertRaises(OverflowError, socket.htonl, k)
            self.assertRaises(OverflowError, socket.htons, k) 
Example 18
Project: aumfor   Author: virtualrealitysystems   File: linux.py    License: GNU General Public License v3.0 5 votes vote down vote up
def src_port(self):
        if hasattr(self, "sport"):
            return socket.htons(self.sport)
        elif hasattr(self, "inet_sport"):
            return socket.htons(self.inet_sport)
        else:
            return None 
Example 19
Project: aumfor   Author: virtualrealitysystems   File: linux.py    License: GNU General Public License v3.0 5 votes vote down vote up
def dst_port(self):
        if hasattr(self, "sk") and hasattr(self.sk, "__sk_common") and hasattr(self.sk.__sk_common, "skc_portpair"):
            return socket.htons(self.sk.__sk_common.skc_portpair & 0xffff) #pylint: disable-msg=W0212  
        elif hasattr(self, "dport"):
            return socket.htons(self.dport)
        elif hasattr(self, "inet_dport"):
            return socket.htons(self.inet_dport)
        elif hasattr(self, "sk") and hasattr(self.sk, "__sk_common") and hasattr(self.sk.__sk_common, "skc_dport"):
            return socket.htons(self.sk.__sk_common.skc_dport) #pylint: disable-msg=W0212
        else:
            return None 
Example 20
Project: CyberScan   Author: medbenali   File: supersocket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type)) 
Example 21
Project: CyberScan   Author: medbenali   File: inet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def answers(self, other):
        if not isinstance(other, IP):
            return 0
        if not ( ((conf.checkIPsrc == 0) or (self.dst == other.dst)) and
                 (self.src == other.src) and
                 ( ((conf.checkIPID == 0)
                    or (self.id == other.id)
                    or (conf.checkIPID == 1 and self.id == socket.htons(other.id)))) and
                 (self.proto == other.proto) ):
            return 0
        return self.payload.answers(other.payload) 
Example 22
Project: CyberScan   Author: medbenali   File: inet6.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, type = ETH_P_IPV6, filter=None, iface=None, promisc=None, nofilter=0):
        L3RawSocket.__init__(self, type, filter, iface, promisc)
        # NOTE: if fragmentation is needed, it will be done by the kernel (RFC 2292)
        self.outs = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) 
Example 23
Project: CyberScan   Author: medbenali   File: linux.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
        self.type = type
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if iface:
            self.ins.bind((iface, type))
        if not nofilter:
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        if promisc is None:
            promisc = conf.promisc
        self.promisc = promisc
        if self.promisc:
            if iface is None:
                self.iff = get_if_list()
            else:
                if iface.__class__ is list:
                    self.iff = iface
                else:
                    self.iff = [iface]
            for i in self.iff:
                set_promisc(self.ins, i) 
Example 24
Project: CyberScan   Author: medbenali   File: linux.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example 25
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 5 votes vote down vote up
def testNtoH(self):
        # This just checks that htons etc. are their own inverse,
        # when looking at the lower 16 or 32 bits.
        sizes = {socket.htonl: 32, socket.ntohl: 32,
                 socket.htons: 16, socket.ntohs: 16}
        for func, size in sizes.items():
            mask = (1L<<size) - 1
            for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
                self.assertEqual(i & mask, func(func(i&mask)) & mask)

            swapped = func(mask)
            self.assertEqual(swapped & mask, mask)
            self.assertRaises(OverflowError, func, 1L<<34) 
Example 26
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 5 votes vote down vote up
def testNtoHErrors(self):
        good_values = [ 1, 2, 3, 1L, 2L, 3L ]
        bad_values = [ -1, -2, -3, -1L, -2L, -3L ]
        for k in good_values:
            socket.ntohl(k)
            socket.ntohs(k)
            socket.htonl(k)
            socket.htons(k)
        for k in bad_values:
            self.assertRaises(OverflowError, socket.ntohl, k)
            self.assertRaises(OverflowError, socket.ntohs, k)
            self.assertRaises(OverflowError, socket.htonl, k)
            self.assertRaises(OverflowError, socket.htons, k) 
Example 27
Project: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 5 votes vote down vote up
def testNtoH(self):
        # This just checks that htons etc. are their own inverse,
        # when looking at the lower 16 or 32 bits.
        sizes = {socket.htonl: 32, socket.ntohl: 32,
                 socket.htons: 16, socket.ntohs: 16}
        for func, size in sizes.items():
            mask = (1L<<size) - 1
            for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
                self.assertEqual(i & mask, func(func(i&mask)) & mask)

            swapped = func(mask)
            self.assertEqual(swapped & mask, mask)
            self.assertRaises(OverflowError, func, 1L<<34) 
Example 28
Project: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 5 votes vote down vote up
def testNtoHErrors(self):
        good_values = [ 1, 2, 3, 1L, 2L, 3L ]
        bad_values = [ -1, -2, -3, -1L, -2L, -3L ]
        for k in good_values:
            socket.ntohl(k)
            socket.ntohs(k)
            socket.htonl(k)
            socket.htons(k)
        for k in bad_values:
            self.assertRaises(OverflowError, socket.ntohl, k)
            self.assertRaises(OverflowError, socket.ntohs, k)
            self.assertRaises(OverflowError, socket.htonl, k)
            self.assertRaises(OverflowError, socket.htons, k) 
Example 29
Project: Nscan   Author: OffensivePython   File: get.py    License: Apache License 2.0 5 votes vote down vote up
def Network():
    '''
        send a dns query and capture response packet
        Output:
            ifname: interface name
            ifaddr: interface ip address
            ifmac: interface mac address
            gateway: router mac address
    '''
    sniff = socket.socket(socket.AF_PACKET,
                        socket.SOCK_RAW,
                        socket.htons(0x800))
    while True:
        try:
            socket.gethostbyname('www.google.com')
            data, sa_ll = sniff.recvfrom(65535)
            if sa_ll[2] == socket.PACKET_HOST and sa_ll[0]!='lo':
                break
        except:
            print 'Check your internet connection'
            sniff.close()
            sys.exit()
    sniff.close()

    ifname = sa_ll[0] # interface name
    if 'ppp' in ifname:
        ifmac = mac2byte('00:00:00:00:00:00')
        gateway = mac2byte('00:00:00:00:00:00')
        IPHI = 0    # for ppp interfaces
    else:
        ifmac = data[:6] # interface mac address
        gateway = data[6:12] # gateway mac address
        IPHI = 14   # for eth interfaces
    ifaddr = socket.inet_ntoa(data[IPHI+16:IPHI+20]) # interface ip address
    return ifname, ifaddr, ifmac, gateway 
Example 30
Project: Nscan   Author: OffensivePython   File: probe.py    License: Apache License 2.0 5 votes vote down vote up
def send(self, hosts, srcp, gen):
		sock = socket.socket(socket.AF_PACKET,
			socket.SOCK_RAW,
			socket.htons(ETH_P_IP))
		nhosts = hosts[1] - hosts[0]
		eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()
		tcph = tcp.TCP(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))
			except StopIteration:
				break
			for port_list in self.ports:
				for port in range(port_list[0], port_list[1]):
					if self.events['send'].isSet():
						tcph.dstp = port
						packet = eth + iph.pack() + tcph.pack(iph.src, iph.dst)
						sock.sendto(packet, (self.ifname, 0))
						npacket+=1
						if not npacket%self.cooldown[0]:
							time.sleep(self.cooldown[1])
					else:
						break
		logging.info('[SEND] Sent: {} packets'.format(npacket))
		sock.close()