Python socket.ntohs() Examples

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

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

Example 1
Project: Doga   Author: pravj   File: packet.py    License: MIT License 6 votes vote down vote up
def parse(self, ip, packet_string):
        """ Parse required info from packet according Ethernet Header structure
        Reference: http://en.wikipedia.org/wiki/Ethernet_frame#Structure

        param: ip(str): local IP address of machine
        param: packet_string(str): packet string from packet tuple object
        """

        eth_h = packet_string[:ETH_LENGTH]
        unpacked_eth_h = struct.unpack('!6s6sH', eth_h)

        eth_protocol = socket.ntohs(unpacked_eth_h[2])

        if (eth_protocol == 8):
            iph_len, packet_protocol, addr = self.parse_ip_header(
                packet_string)

            if (packet_protocol == 6):
                data, ports = self.parse_tcp_header(packet_string, iph_len)

                if self.verify_packet_data(ip, data, addr, ports):
                    self.payload_parser.parse(data, ports) 
Example 2
Project: flare-fakenet-ng   Author: fireeye   File: winutil.py    License: Apache License 2.0 6 votes vote down vote up
def _get_pid_port_tcp(self, port):

        for item in self.get_extended_tcp_table():

            lPort = socket.ntohs(item.dwLocalPort)
            lAddr = socket.inet_ntoa(struct.pack('L', item.dwLocalAddr))
            pid = item.dwOwningPid

            if lPort == port:
                return pid
        else:
            return None

    ##########################################################################
    # The GetExtendedUdpTable function retrieves a table that contains a list of UDP endpoints available to the application.
    #
    # DWORD GetExtendedUdpTable(
    #   _Out_   PVOID           pUdpTable,
    #   _Inout_ PDWORD          pdwSize,
    #   _In_    BOOL            bOrder,
    #   _In_    ULONG           ulAf,
    #   _In_    UDP_TABLE_CLASS TableClass,
    #   _In_    ULONG           Reserved
    # ); 
Example 3
Project: flare-fakenet-ng   Author: fireeye   File: winutil.py    License: Apache License 2.0 6 votes vote down vote up
def _get_pid_port_udp(self, port):

        for item in self.get_extended_udp_table():

            lPort = socket.ntohs(item.dwLocalPort)
            lAddr = socket.inet_ntoa(struct.pack('L', item.dwLocalAddr))
            pid = item.dwOwningPid

            if lPort == port:
                return pid
        else:
            return None

    ##########################################################################
    # Retrieves the name of the executable file for the specified process.
    #
    # DWORD WINAPI GetProcessImageFileName(
    #   _In_  HANDLE hProcess,
    #   _Out_ LPTSTR lpImageFileName,
    #   _In_  DWORD  nSize
    # ); 
Example 4
Project: rsp   Author: Snawoot   File: transparentlistener.py    License: MIT License 6 votes vote down vote up
def get_orig_dst(sock):
    own_addr = sock.getsockname()[0]
    own_af = detect_af(own_addr)
    if own_af == socket.AF_INET:
        buf = sock.getsockopt(socket.SOL_IP, constants.SO_ORIGINAL_DST, sockaddr_size)
        sa = sockaddr_in.from_buffer_copy(buf)
        addr = socket.ntohl(sa.sin_addr)
        addr = str(addr >> 24) + '.' + str((addr >> 16) & 0xFF) + '.' + str((addr >> 8) & 0xFF) + '.' + str(addr & 0xFF)
        port = socket.ntohs(sa.sin_port)
        return addr, port
    elif own_af == socket.AF_INET6:
        buf = sock.getsockopt(constants.SOL_IPV6, constants.SO_ORIGINAL_DST, sockaddr6_size)
        sa = sockaddr_in6.from_buffer_copy(buf)
        addr = socket.inet_ntop(socket.AF_INET6, sa.sin6_addr)
        port = socket.ntohs(sa.sin_port)
        return addr, port
    else:
        raise RuntimeError("Unknown address family!") 
Example 5
Project: cyber-security-framework   Author: black-security   File: ipv4.py    License: MIT License 6 votes vote down vote up
def __init__(self, buffer: bytes = b""):
        super().__init__()
        self.data_offset = self.ihl * 4
        
        self.raw_buffer = buffer
        self.raw_header = buffer[:self.data_offset]
        
        phbs = {v.value: k for k, v in DSCP.__members__.items()}
        self.dscp = phbs[self.raw_dscp] if self.raw_dscp in phbs else "Unknown PHB"
        self.ecn = "Non-ECT" if self.raw_ecn is 0 else ("ECT(0)" if self.raw_ecn is 2 else ("ECT(1)" if self.raw_ecn is 1 else "CE"))
        self.differentiated_services = (self.dscp, self.ecn)
        self.total_length = socket.ntohs(self.raw_total_length)
        self.identification = socket.ntohs(self.raw_identification)
        self.flags = {0: self.raw_flags&1, 1: self.raw_flags&2, 2: self.raw_flags&4}
        self.protocol = self.protocols[self.raw_protocol] if self.raw_protocol in self.protocols else "Unknown"
        self.checksum = socket.ntohs(self.raw_checksum)
        self.source = socket.inet_ntoa(struct.pack("<L", self.raw_source))
        self.destination = socket.inet_ntoa(struct.pack("<L", self.raw_destination))
        
        self.raw_options = b""
        self.options = None
        if self.ihl > 5:
            self.raw_options = buffer[0x14:self.data_offset]
            self.options = self.options = self.Options(self.raw_options)#self.parse_options(self.raw_options)
        self.data = buffer[self.data_offset:] 
Example 6
Project: vrnetlab   Author: plajjan   File: xcon.py    License: 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 7
Project: PyExfil   Author: ytisf   File: http_exfiltration.py    License: MIT License 6 votes vote down vote up
def listen(local_addr, local_port=80):
	"""
	This function will initiate a web listener (NOT SERVER!) on default port 80.
	It will then capture files and save them into a local file.
	:param local_addr: The ip address to bind to.
	:param local_port: The port. If not mentioned, 80 will be chosen.
	:return:
	"""
	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

	try:
		s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_P_ALL))
	except socket.error, msg:
		sys.stderr.write('Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + "\n")
		raise () 
Example 8
Project: python-scripts   Author: soarpenguin   File: sniff.py    License: GNU General Public License v3.0 6 votes vote down vote up
def decode_ip_packet(s):
    d={}
    d['version']=(ord(s[0]) & 0xf0) >> 4
    d['header_len']=ord(s[0]) & 0x0f
    d['tos']=ord(s[1])
    d['total_len']=socket.ntohs(struct.unpack('H',s[2:4])[0])
    d['id']=socket.ntohs(struct.unpack('H',s[4:6])[0])
    d['flags']=(ord(s[6]) & 0xe0) >> 5
    d['fragment_offset']=socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
    d['ttl']=ord(s[8])
    d['protocol']=ord(s[9])
    d['checksum']=socket.ntohs(struct.unpack('H',s[10:12])[0])
    d['source_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0])
    d['destination_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0])
    if d['header_len']>5:
        d['options']=s[20:4*(d['header_len']-5)]
    else:
        d['options']=None
    d['data']=s[4*d['header_len']:]
    return d 
Example 9
Project: boofuzz   Author: jtpereyda   File: test_session_failure_handling.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bind(self):
        """
        Bind server, and call listen if using TCP, meaning that the client test code can successfully connect.
        """
        if self.proto == "tcp":
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        elif self.proto == "udp":
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        elif self.proto == "raw":
            self.server_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
        else:
            raise Exception("Invalid protocol type: '{0}'".format(self.proto))

        self.server_socket.bind((self.host, 0))  # let OS choose a free port

        if self.proto == "tcp":
            self.server_socket.listen(1)

        self.active_port = self.server_socket.getsockname()[1] 
Example 10
Project: boofuzz   Author: jtpereyda   File: test_socket_connection.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bind(self):
        """
        Bind server, and call listen if using TCP, meaning that the client test code can successfully connect.
        """
        if self.proto == "tcp":
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        elif self.proto == "udp":
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        elif self.proto == "raw":
            self.server_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_P_ALL))
        else:
            raise Exception("Invalid protocol type: '{0}'".format(self.proto))

        self.server_socket.bind((self.host, 0))  # let OS choose a free port

        if self.proto == "tcp":
            self.server_socket.listen(1)

        self.active_port = self.server_socket.getsockname()[1] 
Example 11
Project: iSDX   Author: sdn-ixp   File: arproxy.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # info about non-sdn participants
        # TODO: Create a mapping between actual interface IP addresses
        # and the corresponding MAC addresses for all the non-SDN participants
        # In case of MDS, it is actual mac adresses of these interfaces, in case
        # of the superset scheme it is : 1XXXX-nexthop_id
        # self.nonSDN_nhip_2_nhmac = {}
        try:
            self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_TYPE_ARP))
            self.sock.bind((config.interface, 0))
        except socket.error as msg:
            logger.error("Can't open socket %s", str(config.interface))
            logger.exception('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
            raise 
Example 12
Project: rekall   Author: google   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def ntoh(value):
    size = value.obj_size
    if size == 2:
        return socket.ntohs(value.v())
    elif size == 4:
        return socket.ntohl(value.v())

    from rekall import obj
    return obj.NoneObject("Not a valid integer") 
Example 13
Project: dionaea   Author: DinoTools   File: fieldtypes.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reverse(self, val):
        if self._size == 16:
            val = socket.ntohs(val)
        elif self._size == 32:
            val = socket.ntohl(val)
        return val 
Example 14
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 15
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 16
Project: CyberScan   Author: medbenali   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 17
Project: Doga   Author: pravj   File: sockets.py    License: 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 18
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 19
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 20
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 21
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 22
Project: pynng   Author: codypiersall   File: sockaddr.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        as_bytes = struct.pack('I', self.addr)
        ip = socket.inet_ntop(socket.AF_INET, as_bytes)
        port = socket.ntohs(self.port)
        return '{}:{}'.format(ip, port) 
Example 23
Project: pynng   Author: codypiersall   File: sockaddr.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        # TODO: not a good string repr at all
        ip = socket.inet_ntop(socket.AF_INET6, self.addr)
        port = socket.ntohs(self.port)
        return "[{}]:{}".format(ip, port) 
Example 24
Project: vlcp   Author: hubo1016   File: ethernet.py    License: Apache License 2.0 5 votes vote down vote up
def checksum(data):
    if len(data) % 2:
        data += b'\x00'
    s = sum(array.array('H',data))
    s = (s & 0xffff) + (s >> 16)
    s += (s >> 16)
    return _socket.ntohs(~s & 0xffff) 
Example 25
Project: pycopia   Author: kdart   File: inet.py    License: Apache License 2.0 5 votes vote down vote up
def net2iph(s):
	len = ntohs(gets(s[2:4]))
	id = ntohs(gets(s[4:6]))
	off = ntohs(gets(s[6:8]))
	return s[:2] + mks(len) + mks(id) + mks(off) + s[8:] 
Example 26
Project: pycopia   Author: kdart   File: inet.py    License: Apache License 2.0 5 votes vote down vote up
def net2updh(s):
	sp = ntohs(gets(s[0:2]))
	dp = ntohs(gets(s[2:4]))
	len = ntohs(gets(s[4:6]))
	return mks(sp) + mks(dp) + mks(len) + s[6:] 
Example 27
Project: smod-1   Author: theralfbrown   File: fields.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 28
Project: ipftrace   Author: YutaroHayakawa   File: ipftrace.py    License: Apache License 2.0 5 votes vote down vote up
def _parse_l4_proto(self, event):
        p = str(event.l4_protocol)
        l4_proto = ID_TO_PROTO.get(p, f"Unknown({p})")
        sport = socket.ntohs(event.sport)
        dport = socket.ntohs(event.dport)
        return (l4_proto, sport, dport) 
Example 29
Project: CVE-2016-6366   Author: RiskSense-Ops   File: fields.py    License: MIT License 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 30
Project: mptcp-abuse   Author: Neohapsis   File: fields.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 31
Project: scapy   Author: secdev   File: fields.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            # Replaces socket.ntohs (but work on both little/big endian)
            val = struct.unpack('>H', struct.pack('<H', int(val)))[0]
        elif self.size == 32:
            # Same here but for socket.ntohl
            val = struct.unpack('>I', struct.pack('<I', int(val)))[0]
        return val 
Example 32
Project: Fluid-Designer   Author: Microvellum   File: test_socket.py    License: GNU General Public License v3.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 = (1<<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, 1<<34) 
Example 33
Project: Fluid-Designer   Author: Microvellum   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testNtoHErrors(self):
        good_values = [ 1, 2, 3, 1, 2, 3 ]
        bad_values = [ -1, -2, -3, -1, -2, -3 ]
        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 34
Project: ironpython3   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 = (1<<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, 1<<34) 
Example 35
Project: ironpython3   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, 1, 2, 3 ]
        bad_values = [ -1, -2, -3, -1, -2, -3 ]
        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 36
Project: happy   Author: openweave   File: HappyPacketProcess.py    License: Apache License 2.0 5 votes vote down vote up
def Decode(self, packet):
        ethLength = 14
        ethHeader = packet[:ethLength]
        eth = unpack('!6s6sH', ethHeader)
        self.ethProto = socket.ntohs(eth[2])
        self.ethDest = self.GetEthernetAddr(packet[0:6])
        self.ethSource = self.GetEthernetAddr(packet[6:12])
        self.payload = packet[ethLength:]
        self.parent = self 
Example 37
Project: happy   Author: openweave   File: HappyPacketProcess.py    License: 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 38
Project: ryu   Author: OpenState-SDN   File: packet_utils.py    License: Apache License 2.0 5 votes vote down vote up
def checksum(data):
    data = six.binary_type(data)    # input can be bytearray.
    if len(data) % 2:
        data += b'\x00'

    s = sum(array.array('H', data))
    s = (s & 0xffff) + (s >> 16)
    s += (s >> 16)
    return socket.ntohs(~s & 0xffff)


# avoid circular import 
Example 39
Project: dash-hack   Author: gpwclark   File: fields.py    License: MIT License 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 40
Project: dash-hack   Author: gpwclark   File: fields.py    License: MIT License 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 41
Project: dash-hack   Author: gpwclark   File: fields.py    License: MIT License 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 42
Project: isip   Author: halit   File: fields.py    License: MIT License 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 43
Project: gcblue   Author: gcblue   File: test_socket.py    License: BSD 3-Clause "New" or "Revised" 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 44
Project: gcblue   Author: gcblue   File: test_socket.py    License: BSD 3-Clause "New" or "Revised" 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 45
Project: fenrir-ocd   Author: Orange-Cyberdefense   File: Autoconf.py    License: MIT License 5 votes vote down vote up
def __init__(self):
		self.hostmac = ""
		self.hostip = ""
		self.conf = True
		self.ifaceHost = "em1"
		self.ifaceNetwork = "eth0"
		self.sockHost = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
		self.sockNetwork = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
		try:
			self.sockHost.bind((self.ifaceHost, 0))
			self.sockNetwork.bind((self.ifaceNetwork, 0))
		except:
			#exit("You need 2 physical network interfaces to use FENRIR !")
			print("You need 2 physical network interfaces to use FENRIR !")
		self.inputs = [self.sockHost, self.sockNetwork] 
Example 46
Project: fenrir-ocd   Author: Orange-Cyberdefense   File: FENRIR2.py    License: MIT License 5 votes vote down vote up
def bindAllIface(self):
		self.s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) 
Example 47
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_socket.py    License: GNU General Public License v3.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 = (1<<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, 1<<34) 
Example 48
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testNtoHErrors(self):
        good_values = [ 1, 2, 3, 1, 2, 3 ]
        bad_values = [ -1, -2, -3, -1, -2, -3 ]
        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 49
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testNtoH(self):
        if sys.platform[:4] == 'java': return # problems with int & long
        # 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 50
Project: POC-EXP   Author: ym2011   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reverse(self, val):
        if self.size == 16:
            val = socket.ntohs(val)
        elif self.size == 32:
            val = socket.ntohl(val)
        return val 
Example 51
Project: PythonForWindows   Author: hakril   File: network.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remote_port(self):
        """:type: :class:`int`"""
        if not self.established:
            return None
        return socket.ntohs(self.dwRemotePort) 
Example 52
Project: PythonForWindows   Author: hakril   File: network.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def local_port(self):
        """:type: :class:`int`"""
        return socket.ntohs(self.dwLocalPort) 
Example 53
Project: PythonForWindows   Author: hakril   File: network.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remote_port(self):
        """:type: :class:`int`"""
        if not self.established:
            return None
        return socket.ntohs(self.dwRemotePort) 
Example 54
Project: PythonForWindows   Author: hakril   File: network.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def local_port(self):
        """:type: :class:`int`"""
        return socket.ntohs(self.dwLocalPort) 
Example 55
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 1_5_integer_conversion.py    License: MIT License 5 votes vote down vote up
def convert_integer():
    data = 1234
    # 32-bit
    print ("Original: %s => Long  host byte order: %s, Network byte order: %s" %(data, socket.ntohl(data), socket.htonl(data)))
    # 16-bit
    print ("Original: %s => Short  host byte order: %s, Network byte order: %s" %(data, socket.ntohs(data), socket.htons(data))) 
Example 56
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testNtoH(self):
        if sys.platform[:4] == 'java': return # problems with int & long
        # 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 57
Project: code   Author: grawity   File: net.py    License: MIT License 5 votes vote down vote up
def port(self):
        return socket.ntohs(self.sin_port) 
Example 58
Project: code   Author: grawity   File: net.py    License: MIT License 5 votes vote down vote up
def port(self):
        return socket.ntohs(self.sin6_port) 
Example 59
Project: code   Author: grawity   File: win32-identd.py    License: MIT License 5 votes vote down vote up
def unpack_addr(af, psockaddr):
    if af == socket.AF_INET:
        addr, port = psockaddr
        addr = socket.inet_ntoa(struct.pack("!L", socket.ntohl(addr)))
        port = socket.ntohs(port)
        return addr, port
    elif af == socket.AF_INET6:
        if len(psockaddr) == 2:
            addr, port = psockaddr
            flow, scope = None, None
        elif len(psockaddr) == 4:
            addr, port, flow, scope = psockaddr
        addr = ":".join("%04x" % x for x in struct.unpack("!8H", addr))
        port = socket.ntohs(port)
        return addr, port, flow, scope 
Example 60
Project: grove.py   Author: Seeed-Studio   File: grove_i2c_thermocouple_amplifier_mcp9600.py    License: MIT License 5 votes vote down vote up
def read(self):
        data = self._bus.read_word_data(self._addr, self._junc)
        # Big endian -> little endian
        data = socket.ntohs(data)
        # print("RAW = 0x%X" % data)

        # It's 16-bit 2's complement code
        temperature = ctypes.c_short(data).value / 16.0
        return temperature