Python socket.ntohl() Examples

The following are 30 code examples of socket.ntohl(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def get_netmask(self):
        """
        Get ip network netmask
        """
        if not CTYPES_SUPPORT:
            raise exceptions.TestSkipError("Getting the netmask requires "
                                           "python > 2.4")
        ifreq = struct.pack('16sH14s', self.name.encode(),
                            socket.AF_INET, b'\x00' * 14)
        try:
            res = fcntl.ioctl(sockfd, arch.SIOCGIFNETMASK, ifreq)
        except IOError:
            return 0
        netmask = socket.ntohl(struct.unpack('16sH2xI8x', res)[2])

        return 32 - int(math.log(ctypes.c_uint32(~netmask).value + 1, 2)) 
Example #2
Source File: transparentlistener.py    From rsp with 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 #3
Source File: communication.py    From Software-Architecture-with-Python with MIT License 6 votes vote down vote up
def receive(channel):
    """ Receive a message from a channel """
    
    size = struct.calcsize("L")
    size = channel.recv(size)
    try:
        size = socket.ntohl(struct.unpack("L", size)[0])
    except struct.error as e:
        return ''
    
    buf = ""

    while len(buf) < size:
        buf = channel.recv(size - len(buf))

    return pickle.loads(buf)[0] 
Example #4
Source File: 11_5_integer_conversion.py    From Python-Network-Programming with 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 #5
Source File: 12_3_chat_server_with_select.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def receive(channel):
    size = struct.calcsize("L")
    size = channel.recv(size)
    try:
        size = socket.ntohl(struct.unpack("L", size)[0])
    except struct.error as e:
        return ''
    buf = ""
    while len(buf) < size:
        buf = channel.recv(size - len(buf))
    return pickle.loads(buf)[0] 
Example #6
Source File: test_socket.py    From CTFCrackTools with 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 #7
Source File: WXBizMsgCrypt.py    From wechat-encrypt-python3 with Apache License 2.0 5 votes vote down vote up
def decrypt(self,text,appid):
        """对解密后的明文进行补位删除
        @param text: 密文
        @return: 删除填充补位后的明文
        """
        try:
            cryptor = AES.new(self.key,self.mode,self.key[:16])
            # 使用BASE64对密文进行解码,然后AES-CBC解密
            plain_text  = cryptor.decrypt(base64.b64decode(text))
        except Exception as e:
            logger.exception('wechat encryption/decryption error')
            return  ierror.WXBizMsgCrypt_DecryptAES_Error,None
        try:
            pad = plain_text[-1]
            # 去掉补位字符串
            #pkcs7 = PKCS7Encoder()
            #plain_text = pkcs7.encode(plain_text)
            # 去除16位随机字符串
            content = plain_text[16:-pad]
            xml_len = socket.ntohl(struct.unpack("I",content[ : 4])[0])
            xml_content = content[4 : xml_len+4]
            from_appid = utf8_bytes_to_str(content[xml_len+4:])
        except Exception as e:
            logger.exception('wechat encryption/decryption error')
            return  ierror.WXBizMsgCrypt_IllegalBuffer,None
        if  from_appid != appid:
            return ierror.WXBizMsgCrypt_ValidateAppid_Error,None
        return 0,xml_content 
Example #8
Source File: WXBizMsgCrypt.py    From wechat_mall with MIT License 5 votes vote down vote up
def decrypt(self, text, appid):
        """对解密后的明文进行补位删除
        @param text: 密文
        @return: 删除填充补位后的明文
        """
        try:
            cryptor = AES.new(self.key, self.mode, self.key[:16])
            # 使用BASE64对密文进行解码,然后AES-CBC解密
            plain_text = cryptor.decrypt(base64.b64decode(text))
        except Exception:
            return WXBizMsgCrypt_DecryptAES_Error, None
        try:
            pad = plain_text[-1]
            # 去掉补位字符串
            # pkcs7 = PKCS7Encoder()
            # plain_text = pkcs7.encode(plain_text)
            # 去除16位随机字符串
            content = plain_text[16:-pad]
            xml_len = socket.ntohl(struct.unpack(b"I", content[:4])[0])
            xml_content = content[4:xml_len+4]
            from_appid = smart_bytes(content[xml_len+4:])
        except Exception:
            return WXBizMsgCrypt_IllegalBuffer, None
        if from_appid != smart_bytes(appid):
            return WXBizMsgCrypt_ValidateAppid_Error, None
        return 0, xml_content 
Example #9
Source File: fields.py    From arissploit with 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 #10
Source File: base.py    From dingtalk-sdk with GNU General Public License v3.0 5 votes vote down vote up
def _decrypt(self, text, _id, exception=None):
        text = to_binary(text)
        plain_text = self.cipher.decrypt(base64.b64decode(text))
        padding = byte2int(plain_text[-1])
        content = plain_text[16:-padding]
        xml_length = socket.ntohl(struct.unpack(b'I', content[:4])[0])
        xml_content = to_text(content[4:xml_length + 4])
        from_id = to_text(content[xml_length + 4:])
        if from_id != _id:
            exception = exception or Exception
            raise exception()
        return xml_content 
Example #11
Source File: fields.py    From kamene with 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 #12
Source File: fields.py    From POC-EXP with 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 #13
Source File: WEGOBizMsgCrypt.py    From wego with Apache License 2.0 5 votes vote down vote up
def decrypt(self, text):
        """对解密后的明文进行补位删除
        @param text: 密文
        @return: 删除填充补位后的明文
        """
        try:
            cryptor = AES.new(self.key, self.mode, self.key[:16])
            # 使用BASE64对密文进行解码,然后AES-CBC解密
            plain_text = cryptor.decrypt(base64.b64decode(text))
        except Exception:
            # print e
            return Crypt_DecryptAES_Error, None
        try:
            if PY2:
                pad = ord(plain_text[-1])
            else:
                pad = plain_text[-1]
            # 去掉补位字符串
            # pkcs7 = PKCS7Encoder()
            # plain_text = pkcs7.encode(plain_text)
            # 去除16位随机字符串
            content = plain_text[16:-pad]
            xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0])
            xml_content = content[4: xml_len + 4]
            from_appid = content[xml_len + 4:].decode("utf8")
        except Exception:
            return Crypt_IllegalBuffer, None
        if from_appid != self.appid:
            return Crypt_ValidateAppid_Error, None
        return 0, xml_content 
Example #14
Source File: base.py    From wechat-python-sdk with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decrypt(self, text, appid):
        """对解密后的明文进行补位删除

        @param text: 密文
        @return: 删除填充补位后的明文
        """
        try:
            cryptor = AES.new(self.key, self.mode, self.key[:16])
            # 使用BASE64对密文进行解码,然后AES-CBC解密
            plain_text = cryptor.decrypt(base64.b64decode(text))
        except Exception as e:
            raise DecryptAESError(e)

        try:
            if six.PY2:
                pad = ord(plain_text[-1])
            else:
                pad = plain_text[-1]
            # 去掉补位字符串
            # pkcs7 = PKCS7Encoder()
            # plain_text = pkcs7.encode(plain_text)
            # 去除16位随机字符串
            content = plain_text[16:-pad]
            xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0])
            xml_content = content[4: xml_len + 4]
            from_appid = content[xml_len + 4:]
        except Exception as e:
            raise IllegalBuffer(e)
        if from_appid != appid:
            raise ValidateAppIDError()
        return xml_content 
Example #15
Source File: route.py    From CUP with Apache License 2.0 5 votes vote down vote up
def _raw2view(self, r):
        """
        change raw route_info to be readable
        :param r:
            raw route_info
        :return:
            readable route_info
        """
        res = copy.deepcopy(r)
        res['Destination'] = self._int2ip(
            socket.ntohl(int(r['Destination'], 16))
        )
        res['Gateway'] = self._int2ip(socket.ntohl(int(r['Gateway'], 16)))
        res['Mask'] = self._int2ip(socket.ntohl(int(r['Mask'], 16)))
        return res 
Example #16
Source File: route.py    From CUP with Apache License 2.0 5 votes vote down vote up
def get_route_by_ip(self, ip):
        """
        get the route_info which can reach to the ip address
        :param ip:
            destination ip address
        :return:
            route_info in type of dict
        """
        if self._ip_check(ip) is False:
            return None
        i_ip = socket.ntohl(int(self._ip2int(ip)))
        raw_route = self._raw
        ret = None
        for r in raw_route:
            if int(r['Destination'], 16) == i_ip & int(r['Mask'], 16):
                if ret is None:
                    ret = r
                    continue

                old = int(ret['Destination'], 16) & int(ret['Mask'], 16)
                new = int(r['Destination'], 16) & int(r['Mask'], 16)
                if old < new:
                    ret = r
                elif old == new:
                    if int(ret['Metric']) < int(r['Metric']):
                        ret = r
        return self._raw2view(ret) 
Example #17
Source File: win32-identd.py    From code with 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 #18
Source File: GetJapIP.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def Ip2Int(ip):
	return socket.ntohl(struct.unpack("I",socket.inet_aton(str(ip)))[0]) 
Example #19
Source File: 2_3_chat_server_with_select.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def receive(channel):
    size = struct.calcsize("L")
    size = channel.recv(size)
    try:
        size = socket.ntohl(struct.unpack("L", size)[0])
    except struct.error as e:
        return ''
    buf = ""
    while len(buf) < size:
        buf = channel.recv(size - len(buf))
    return pickle.loads(buf)[0] 
Example #20
Source File: test_socket.py    From medicare-demo with 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 #21
Source File: test_socket.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def 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 #22
Source File: test_socket.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def 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 #23
Source File: test_socket.py    From gcblue with 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 #24
Source File: test_socket.py    From gcblue with 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 #25
Source File: fields.py    From isip with 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 #26
Source File: fields.py    From dash-hack with 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 #27
Source File: fields.py    From dash-hack with 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 #28
Source File: fields.py    From dash-hack with 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 #29
Source File: base.py    From wechatpy with MIT License 5 votes vote down vote up
def _decrypt(self, text, _id, exception=None):
        text = to_binary(text)
        plain_text = self.cipher.decrypt(base64.b64decode(text))
        padding = plain_text[-1]
        content = plain_text[16:-padding]
        xml_length = socket.ntohl(struct.unpack(b"I", content[:4])[0])
        xml_content = to_text(content[4 : xml_length + 4])
        from_id = to_text(content[xml_length + 4 :])
        if from_id != _id:
            exception = exception or Exception
            raise exception()
        return xml_content 
Example #30
Source File: recipe-577191.py    From code with MIT License 5 votes vote down vote up
def __toh(self):
        return socket.ntohl(self._int)