Python socket.htonl() Examples

The following are code examples for showing how to use socket.htonl(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: psystem   Author: gokhanm   File: network.py    (license) View Source Project 6 votes vote down vote up
def netmask(self, interface_name, netmask):
        """
            Checking interface first, if interface name found in Get().interfaces()
            validating Ipv4. After that applied ip address to interace

            interface_name = Applied Interface
            netmask = New netmask ip address
        """
        interface_check = Get().interfaces
        valid_ipv4 = validators.ipv4(netmask)

        if not interface_name in interface_check:
            raise WrongInterfaceName("Wrong Interface Name %s" % interface_name)
        elif not valid_ipv4 is True:
            raise NotValidIPv4Address("Not Valid IPv4 Address %s" % netmask)
        else:
            prefix_len = self.get_net_size(netmask.split('.'))
            ifname = interface_name.encode(encoding='UTF-8')
            netmask = ctypes.c_uint32(~((2 ** (32 - prefix_len)) - 1)).value
            nmbytes = socket.htonl(netmask)
            ifreq = struct.pack('16sH2sI8s', ifname, AF_INET, b'\x00'*2, nmbytes, b'\x00'*8) 
            fcntl.ioctl(self.sock, SIOCSIFNETMASK, ifreq) 
Example 2
Project: wechat   Author: zgliujiangang   File: WXBizMsgCrypt.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self,text,appid):
        """???????
        @param text: ???????
        @return: ????????
        """
        # 16?????????????
        text = self.get_random_str() + struct.pack("I",socket.htonl(len(text))) + text + appid
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??
        cryptor = AES.new(self.key,self.mode,self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
        except Exception,e:
            #print e
            return  ierror.WXBizMsgCrypt_EncryptAES_Error,None 
Example 3
Project: wechat-async-sdk   Author: ihjmh   File: base.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self, text, appid):
        """???????

        @param text: ???????
        @return: ????????
        """
        # 16?????????????
        text = self.get_random_str() + struct.pack("I", socket.htonl(len(text))) + to_binary(text) + appid
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??
        cryptor = AES.new(self.key, self.mode, self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return base64.b64encode(ciphertext)
        except Exception as e:
            raise EncryptAESError(e) 
Example 4
Project: weixin-sdk   Author: xfan001   File: WXBizMsgCrypt.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self,text,appid):
        """???????
        @param text: ???????
        @return: ????????
        """
        # 16?????????????
        text = self.get_random_str() + struct.pack("I",socket.htonl(len(text))) + text + appid
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??
        cryptor = AES.new(self.key,self.mode,self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
        except Exception,e:
            #print e
            return  ierror.WXBizMsgCrypt_EncryptAES_Error,None 
Example 5
Project: wechat_mall   Author: a741424975game   File: WXBizMsgCrypt.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self, text, appid):
        """???????
        @param text: ???????
        @return: ????????
        """
        # 16?????????????
        pack_str = struct.pack(b"I", socket.htonl(len(text)))
        text = smart_bytes(self.get_random_str()) + pack_str + smart_bytes(text) + smart_bytes(appid)
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??
        cryptor = AES.new(self.key, self.mode, self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
        except Exception:
            return WXBizMsgCrypt_EncryptAES_Error, None 
Example 6
Project: weixincrop   Author: tonghou23   File: WXBizMsgCrypt.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self,text,corpid):
        """???????
        @param text: ???????
        @return: ????????
        """      
        # 16?????????????
        text = self.get_random_str() + struct.pack("I",socket.htonl(len(text))) + text + corpid
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??    
        cryptor = AES.new(self.key,self.mode,self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
        except Exception,e:
            print e 
            return  ierror.WXBizMsgCrypt_EncryptAES_Error,None 
Example 7
Project: zabbix_wechat   Author: linuxyan   File: WXBizMsgCrypt.py    (license) View Source Project 6 votes vote down vote up
def encrypt(self,text,corpid):
        """???????
        @param text: ???????
        @return: ????????
        """      
        # 16?????????????
        text = self.get_random_str() + struct.pack("I",socket.htonl(len(text))) + text + corpid
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??    
        cryptor = AES.new(self.key,self.mode,self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext)
        except Exception,e:
            print e 
            return  ierror.WXBizMsgCrypt_EncryptAES_Error,None 
Example 8
Project: code   Author: ActiveState   File: recipe-457669.py    (MIT License) View Source Project 5 votes vote down vote up
def send(channel, *args):
    buf = marshall(args)
    value = htonl(len(buf))
    size = struct.pack("L", value)
    channel.send(size)
    channel.send(buf) 
Example 9
Project: hwfw-tool   Author: LeeXiaolan   File: hwfw.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def toString(self, noItemData=True):
    self.header.fileLength = (
        self.header._FORMAT.size 
        + self.header.itemCount * HuaweiFirmwareItem._FORMAT.size
        - 0x4c # FIXME: Can not find where does this bias come from.
    )
    strs = [
      self.header.toString()[20:], # Partial header used for calculate CRC32 value.
    ]
    if self.header.extraHeaderLength:
      strs.append(self.extraHeader)
      self.header.fileLength += len(self.extraHeader)
    data = []
    for item in self.items:
      strs.append(item.toString())
      data.append(item.data)
      self.header.fileLength += item.size
    # Convert to big endian.
    self.header.fileLength = socket.htonl(self.header.fileLength)

    # Update header CRC32 value.
    self.header.headerCrc = seqCrc32(strs)

    if not noItemData:
      strs.extend(data)
      # All data are present, now update file CRC32 value.
      strs[0] = self.header.toString()[12:]
      self.header.fileCrc = seqCrc32(strs)

    # Using the latest header with correct CRC32 value and file length.
    strs[0] = self.header.toString()
    return ''.join(strs) 
Example 10
Project: my-weather-indicator   Author: atareao   File: networkmanayer.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def route_to_dbus(route, family):
        addr, netmask, gateway, metric = route
        return [
            fixups.addr_to_dbus(addr, family),
            fixups.mask_to_dbus(netmask),
            fixups.addr_to_dbus(gateway, family),
            socket.htonl(metric)
        ]


# Constants below are generated with makeconstants.py. Do not edit manually. 
Example 11
Project: Software-Architecture-with-Python   Author: PacktPublishing   File: communication.py    (license) View Source Project 5 votes vote down vote up
def send(channel, *args):
    """ Send a message to a channel """
    
    buf = pickle.dumps(args)
    value = socket.htonl(len(buf))
    size = struct.pack("L",value)
    channel.send(size)
    channel.send(buf) 
Example 12
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 2_3_chat_server_with_select.py    (license) View Source Project 5 votes vote down vote up
def send(channel, *args):
    buffer = pickle.dumps(args)
    value = socket.htonl(len(buffer))
    size = struct.pack("L",value)
    channel.send(size)
    channel.send(buffer) 
Example 13
Project: Python-Network-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: 1_5_integer_conversion.py    (license) View Source Project 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 14
Project: wego   Author: wegostudio   File: WEGOBizMsgCrypt.py    (license) View Source Project 5 votes vote down vote up
def encrypt(self, xml):
        """???????
        @param text: ???????
        @return: ????????
        """
        # 16?????????????
        xml = xml.encode('utf-8')
        if PY2:
            text = self.get_random_str() +\
                struct.pack("I", socket.htonl(len(xml))) + xml + self.appid
        else:
            text = self.get_random_str().encode('utf-8') +\
                struct.pack("I", socket.htonl(len(xml))) +\
                xml + self.appid.encode('utf-8')
        # ???????????????????
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # ??
        cryptor = AES.new(self.key, self.mode, self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # ??BASE64????????????
            result = base64.b64encode(ciphertext).decode("utf8")
            return Crypt_OK, result
        except Exception:
            return Crypt_EncryptAES_Error, None 
Example 15
Project: heartbreaker   Author: lokori   File: network.py    (license) View Source Project 5 votes vote down vote up
def handle_write(self):
            while len(self.buffer) > 0:
                payload, params = self.buffer.pop(0)
                sndrcvinfo = sctp.sndrcvinfo()
                sndrcvinfo.ppid = socket.htonl(params.get('ppid',0))
                fromaddr,flags,msg,notif="",128,payload[:1460],sndrcvinfo
                sent = self.sctp_send(msg,ppid=sndrcvinfo.ppid,flags=notif.flags) 
Example 16
Project: zippy   Author: securesystemslab   File: test_socket.py    (license) View Source Project 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 17
Project: zippy   Author: securesystemslab   File: test_socket.py    (license) View Source Project 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, ValueError), socket.ntohl, k)
            self.assertRaises((OverflowError, ValueError), socket.ntohs, k)
            self.assertRaises((OverflowError, ValueError), socket.htonl, k)
            self.assertRaises((OverflowError, ValueError), socket.htons, k) 
Example 18
Project: chatRoom   Author: JINLINBI   File: client.py    (license) View Source Project 5 votes vote down vote up
def send(channel,*args):
    buffers=pickle.dumps(args)
    value=socket.htonl(len(buffers))
    size=struct.pack("L",value)
    channel.send(size)
    channel.send(buffers) 
Example 19
Project: oil   Author: oilshell   File: test_socket.py    (license) View Source Project 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 20
Project: oil   Author: oilshell   File: test_socket.py    (license) View Source Project 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 21
Project: python2-tracer   Author: extremecoders-re   File: test_socket.py    (license) View Source Project 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 22
Project: python2-tracer   Author: extremecoders-re   File: test_socket.py    (license) View Source Project 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 23
Project: mysql_backup_client   Author: daiguadaidai   File: toolkit.py    (license) View Source Project 5 votes vote down vote up
def num2ip(self, num):
        """???10???????IP
        Args:
            num: ????
        Return:
            ???? ??? IP
            ?: 10.10.10.11
        Raise: None
        """

        return socket.inet_ntoa(struct.pack('I', socket.htonl(num))) 
Example 24
Project: web_ctp   Author: molebot   File: test_socket.py    (license) View Source Project 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 25
Project: web_ctp   Author: molebot   File: test_socket.py    (license) View Source Project 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 26
Project: pefile.pypy   Author: cloudtracer   File: test_socket.py    (license) View Source Project 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 27
Project: pefile.pypy   Author: cloudtracer   File: test_socket.py    (license) View Source Project 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, ValueError), socket.ntohl, k)
            self.assertRaises((OverflowError, ValueError), socket.ntohs, k)
            self.assertRaises((OverflowError, ValueError), socket.htonl, k)
            self.assertRaises((OverflowError, ValueError), socket.htons, k) 
Example 28
Project: ouroboros   Author: pybee   File: test_socket.py    (license) View Source Project 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 29
Project: ouroboros   Author: pybee   File: test_socket.py    (license) View Source Project 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 30
Project: ndk-python   Author: gittor   File: test_socket.py    (license) View Source Project 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 31
Project: ndk-python   Author: gittor   File: test_socket.py    (license) View Source Project 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 32
Project: ops_agent   Author: sjqzhang   File: ip_util.py    (license) View Source Project 5 votes vote down vote up
def int_to_ip(int_ip):
    return socket.inet_ntoa(struct.pack('I',socket.htonl(int_ip))) 
Example 33
Project: ops_agent   Author: sjqzhang   File: easy_session.py    (license) View Source Project 5 votes vote down vote up
def int_to_ip(self, int_ip):
        return socket.inet_ntoa(struct.pack('I', socket.htonl(int_ip))) 
Example 34
Project: oejia_wx   Author: JoneXiong   File: base.py    (license) View Source Project 5 votes vote down vote up
def _encrypt(self, text, _id):
        text = to_binary(text)
        tmp_list = []
        tmp_list.append(to_binary(self.get_random_string()))
        length = struct.pack(b'I', socket.htonl(len(text)))
        tmp_list.append(length)
        tmp_list.append(text)
        tmp_list.append(to_binary(_id))

        text = b''.join(tmp_list)
        text = PKCS7Encoder.encode(text)

        ciphertext = to_binary(self.cipher.encrypt(text))
        return base64.b64encode(ciphertext) 
Example 35
Project: kbe_server   Author: xiaohaoppy   File: test_socket.py    (license) View Source Project 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 36
Project: kbe_server   Author: xiaohaoppy   File: test_socket.py    (license) View Source Project 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 37
Project: minion   Author: alibaba   File: test_tracker.py    (license) View Source Project 5 votes vote down vote up
def int_to_ipstr(int_ip):
    return socket.inet_ntoa(
            struct.pack('I', socket.htonl(int_ip))
            ) 
Example 38
Project: TornadoWeb   Author: VxCoder   File: base.py    (license) View Source Project 5 votes vote down vote up
def _encrypt(self, text, _id):
        text = to_binary(text)
        tmp_list = []
        tmp_list.append(to_binary(self.get_random_string()))
        length = struct.pack(b'I', socket.htonl(len(text)))
        tmp_list.append(length)
        tmp_list.append(text)
        tmp_list.append(to_binary(_id))

        text = b''.join(tmp_list)
        text = PKCS7Encoder.encode(text)

        ciphertext = to_binary(self.cipher.encrypt(text))
        return base64.b64encode(ciphertext) 
Example 39
Project: Aquila   Author: thinkdb   File: functions.py    (license) View Source Project 5 votes vote down vote up
def num2ip(arg, int_ip):
    """
    IP address and number conversion
    arg == ip, Convert digital to IP address
    """
    if arg == 'ip':
        ip = socket.inet_ntoa(struct.pack('I', socket.htonl(int_ip)))
    else:
        ip = str(socket.ntohl(struct.unpack('I', socket.inet_aton(int_ip))[0]))
    return ip 
Example 40
Project: Aquila   Author: thinkdb   File: udf_filter.py    (license) View Source Project 5 votes vote down vote up
def num2ip(arg, int_ip):
    """
    IP address and number conversion
    """
    if arg == 'ip':
        ip = socket.inet_ntoa(struct.pack('I', socket.htonl(int_ip)))
    else:
        ip = str(socket.ntohl(struct.unpack('I', socket.inet_aton(int_ip))[0]))
    return ip 
Example 41
Project: 011_python_network_programming_cookbook_demo   Author: jerry-0824   File: 01_05_integer_conversion.py    (license) View Source Project 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 42
Project: 011_python_network_programming_cookbook_demo   Author: jerry-0824   File: 02_03_chat_server_with_select.py    (license) View Source Project 5 votes vote down vote up
def send(channel, *args):
    buffer = cPickle.dumps(args)
    value = socket.htonl(len(buffer))
    size = struct.pack("L", value)
    channel.send(size)
    channel.send(buffer) 
Example 43
Project: CyberScan   Author: medbenali   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    f=open("/proc/net/route","r")
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 44
Project: hostapd-mana   Author: adde88   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","r")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 45
Project: CVE-2016-6366   Author: RiskSense-Ops   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    f=open("/proc/net/route","r")
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 46
Project: hakkuframework   Author: 4shadoww   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","rb")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(int(dst,16))&0xffffffff,
                       socket.htonl(int(msk,16))&0xffffffff,
                       scapy.utils.inet_ntoa(struct.pack("I",int(gw,16))),
                       iff.decode('utf-8'), ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 47
Project: trex-http-proxy   Author: alwye   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","r")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 48
Project: trex-http-proxy   Author: alwye   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","rb")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(int(dst,16))&0xffffffff,
                       socket.htonl(int(msk,16))&0xffffffff,
                       scapy.utils.inet_ntoa(struct.pack("I",int(gw,16))),
                       iff.decode('utf-8'), ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 49
Project: scapy-bpf   Author: guedou   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","r")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############ 
Example 50
Project: sslstrip-hsts-openwrt   Author: adde88   File: linux.py    (license) View Source Project 4 votes vote down vote up
def read_routes():
    try:
        f=open("/proc/net/route","r")
    except IOError:
        warning("Can't open /proc/net/route !")
        return []
    routes = []
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME))
    addrfamily = struct.unpack("h",ifreq[16:18])[0]
    if addrfamily == socket.AF_INET:
        ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME))
        msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
        dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
        ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
        routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
    else:
        warning("Interface lo: unkown address family (%i)"% addrfamily)

    for l in f.readlines()[1:]:
        iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
        flags = int(flags,16)
        if flags & RTF_UP == 0:
            continue
        if flags & RTF_REJECT:
            continue
        try:
            ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
        except IOError: # interface is present in routing tables but does not have any assigned IP
            ifaddr="0.0.0.0"
        else:
            addrfamily = struct.unpack("h",ifreq[16:18])[0]
            if addrfamily == socket.AF_INET:
                ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
            else:
                warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
                continue
        routes.append((socket.htonl(long(dst,16))&0xffffffffL,
                       socket.htonl(long(msk,16))&0xffffffffL,
                       scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))),
                       iff, ifaddr))
    
    f.close()
    return routes

############
### IPv6 ###
############