最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结。
network (= big-endian) standard none 使用方法是放在fmt的第一个位置,就像’@5s6sif’ 1.1 struct.pack(fmt,v1,v2,…) 将v1,v2 2.代码示例 import struct # native byteorder buffer = struct.pack("ihb", 1, 2, 3) print(repr(buffer)) ''' ihb", buffer)) ''' (1, 2, 3) ''' # data from a sequence, network byteorder data = [1, 2, 3] buffer = struct.pack struct的pack函数把任意数据类型变成bytes: >>> import struct >>> struct.pack('>I', 10240099) b'\x00\x9c@c' pack的第一个参数是处理指令
) # rop += struct.pack('<L',0x7c379c10) # add ebp,eax rop += struct.pack('<L',0x7c34728e) # pop eax rop += struct.pack('<L',0x7c34373a) # pop ebx rop += struct.pack('<L',0xffffffff) # rop += struct.pack ('<L',0x7c345255) # inc ebx rop += struct.pack('<L',0x7c352174) # add ebx,eax rop += struct.pack( ) # neg edx rop += struct.pack('<L',0x7c36ba51) # pop ecx rop += struct.pack('<L',0x7c38f2f4) # &writetable rop += struct.pack('<L',0x7c34a490) # pop edi rop += struct.pack('<L',0x7c346c0b) #
('i', MAGIC)[::-1]) dos.write(struct.pack('i', fileSize)[::-1]) # TOC tocSize = HEADER_SIZE + (len(entries ) * HEADER_SIZE) dos.write(struct.pack('i', toInt(TOC))[::-1]) dos.write(struct.pack('i', tocSize)[:: -1]) for e in entries: dos.write(struct.pack('i', toInt(e.get('type')))[::-1]) dos.write(struct.pack ('i', HEADER_SIZE + e.get('size'))[::-1]) # Data for index, e in enumerate(entries): dos.write(struct.pack ('i', toInt(e.get('type')))[::-1]) dos.write(struct.pack('i', HEADER_SIZE + e.get('size'))[::-1])
j = (j + S[i])%N temp = S[i] S[i] = S[j] S[j] = temp pout += struct.pack 'H',data)) # short->bytes def unCoding(data): d=b'' for i in range(len(data)): d += struct.pack = len(Keyt) Key=b'' r=0 for i in range(32): k=(Keyt[r%pl]+i)%256 Key+= struct.pack 1 return Key #更新密钥 def UpdataKey(Keyt): Key = unCoding(Keyt) #循环左移 Key = Key[1:] + struct.pack fin.seek(0,0) fout.write(struct.pack('I',filelen)) while 1: #读数据
bin文件的python struct库 读写属性 a = struct.pack('B',0x00) b = struct.unpack(‘B’,a) 这块可以使用python编译的看一下哦 (你就明白了) 1. struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型, 可以把这里的字符串理解为字节流,或字节数组)。 其函数原型为:struct.pack(fmt, v1, v2, ...), 参数fmt是格式字符串,关于格式字符串的相关信息在下面有所介绍。v1, v2, ...表示要转换的python值。 2. struct.unpack做的工作刚好与struct.pack相反,用于将字节流转换成python数据类型。 ('I',0x12345678) #四字节存入,正常状态 b = struct.pack(' c = struct.pack('>I',0x12345678) #四字节存入,按大端存储 file.write
127.0.0.1:6379> EVAL 'local a;a=struct.pack("ll",56,78);local x=redis.call("set","k1",a);return x;' 0 设置初始值(覆盖原有的,如果存在) 127.0.0.1:6379> EVAL 'local a;a=struct.pack("lll",56,78,99);local x=redis.call("set > eval 'local x=redis.call("get","k1");local m,n,l=struct.unpack("lll",x);m=m+1;n=n+1;l=l+1;local a=struct.pack AOF文件 上述操作对应的AOF文件内容: $ tail -f appendonly-6379.aof *2 $6 SELECT $1 0 *3 $4 EVAL $76 local a;a=struct.pack ("ll",56,78);local x=redis.call("set","k1",a);return x; $1 0 *3 $4 EVAL $80 local a;a=struct.pack("lll
于是就是有了gtid += struct.pack('<QQ',*[int(_x) for _x in y.split("-")]) 这种看起来不友好, 但又简单实用的写法了. None else tdatadata = data.replace("\n","")gtid_number = 0ldata = data.rstrip(",").split(",")gtid = struct.pack ('<Q',len(_data[1:]))for y in _data[1:]:gtid += struct.pack('<QQ',*[int(_x) for _x in y.split("-")])return ('<Q',len(_data[1:]))for y in _data[1:]:gtid += struct.pack('<QQ',*[int(_x) for _x in y.split("-")])return _next_seq_id = 0bdata = struct.pack('<B',3) + sql.encode()self.write_pack(bdata)#return self.result()
TcpLenres = (TcpHdrLen / 4 << 4 | 0) TcpSeq = socket.htonl(int(time.time())) Buffer = struct.pack 0,TcpLenres,2,socket.htons(8192),0,0) TcpChecksum = SetPacketCheckSum(Buffer) Buffer = struct.pack socket.IPPROTO_TCP,0,IpSourceIP,IpDestIP) IpChecksum = SetPacketCheckSum(Buffer) tcpcsp = struct.pack ("L",TcpChecksum) ipcsp = struct.pack("L",IpChecksum) return struct.pack("BBHHHBBHLLHHLLBBHHH
H",0xfa) extra_len = "\x00" data_type = "\x00" vbucket = "\x00\x00" body_len = struct.pack("! I",0) opaque = struct.pack("!I",0) CAS = struct.pack("! I",0xffffffd0) opaque = struct.pack("!I",0) CAS = struct.pack("! Q",0) extras_flags = 0xdeadbeef extras_expiry = struct.pack("! H",32) body_len = struct.pack("!
B',0x81) length = len(text) if length <= 125: sendData += struct.pack B',length) elif length <= 65536: sendData += struct.pack('! B',126) sendData += struct.pack('! H',length) elif length == 127: sendData += struct.pack('! B',127) sendData += struct.pack('!Q',length) sendData += struct.pack('!
offset开始的缓冲区,并返回解析结果 支持的格式 image.png 实战 格式的使用: # -*- coding: utf-8 -*- import struct a=1 b=-1 print(struct.pack ("h",b)) print(struct.pack("i",b)) image.png 二进制文件读写: # -*- coding: utf-8 -*- import struct a=1000 b= -1000 f=open("111.bin","wb") f.write(struct.pack("h",a))#对a装包,并写入 f.write(struct.pack("i",b)) f.close
('>H', 0x000B) # B-node, Register # Questions: 1 questions = struct.pack('>H', 1) # Answer RRs: 0 answer_rrs = struct.pack('>H', 0) # Authority RRs: 0 authority_rrs = struct.pack('>H nb_name.encode('ascii')[:15].ljust(15, b'\x00') # Truncate/pad to 15 nb_section = b'\xC0' * 2 + struct.pack \x00' # Compressed pointer hack + name # QType: NB (0x0020), QClass: IN (0x0001) qtype = struct.pack ('>H', 0x0020) qclass = struct.pack('>H', 0x0001) question = nb_section + qtype + qclass
struct.pack('<L', server_id) + struct.pack('<%dp' % min(MAX_STRING_LEN, lhostname + 1) , lusername + 1), self.username.encode()) + struct.pack('<% ('<H', self.port) + struct.pack('<l', 0) + struct.pack('<l', master_id) prelude += struct.pack('<I', 4) flags = 0 if not self. <H', flags) prelude += struct.pack('<I', self.
classmethoddef HandshakeV10(self,salt,version,capability_flags):bdata = b'\n' + version + b'\x00' + struct.pack ('<L',6666) + salt[:8] + b'\x00' + capability_flags[:2] + struct.pack('<B',33) + struct.pack('<H',2) \x00'if isinstance(row[0][x],int):t += struct.pack('<LB',len(str(row)),3) #3:MYSQL_TYPE_LONG else:t + = struct.pack('<LB',len(str(row)),253) #253:MYSQL_TYPE_VAR_STRINGt += b'\x00\x00\x00\x00\x00'bdata.append _open(dbname)#self.database = dbname_tdata = b'\x00\x00\x00\x02@\x00\x00\x00'_t = b'\x01' + struct.pack
('B', val) elif 2**7<val<=2**15: temps += '\x02\x02' + struct.pack('! H', val) elif 2**15<val<=2**23: temps += '\x02\x03' + struct.pack('! I', val)[1:] elif 2**23<val<=2**31: temps += '\x02\x04' + struct.pack('! 此函数直接返回长度字段的编码结果 if slen<=127: return struct.pack('B', slen) if 127<slen< struct.pack('!
(struct.pack("<L", self.dst)) # 协议类型 try: self.protocol = self.protocol_map ("<L",self.src)) self.dst_address = socket.inet_ntoa(struct.pack("<L",self.dst)) 为 ("src", c_uint32), ("dst", c_uint32) self.src_address = socket.inet_ntoa(struct.pack("@I",self.src )) self.dst_address = socket.inet_ntoa(struct.pack("@I",self.dst)) """ import socket import os import ("@I", self.src)) self.dst_address = socket.inet_ntoa(struct.pack("@I", self.dst)) try
TFTP数据包的格式 相关代码 pack 和unpack import struct data = struct.pack('! socket.AF_INET,socket.SOCK_DGRAM) #服务器地址 destAddr = ('192.168.11.74',69) #pack信息 data = struct.pack #获取数据,写到文件中 myFile.write(recvData[4:]) #准备ack数据 ackData = struct.pack socket.AF_INET,socket.SOCK_DGRAM) #服务器地址 destAddr = ('192.168.11.74',69) #pack信息 data = struct.pack blockNum += 1 if blockNum == 65536: blockNum = 0 blockDate1 = struct.pack
def demo1(): # 使用bin_buf = struct.pack(fmt, buf)将buf为二进制数组bin_buf # 使用buf = struct.unpack(fmt , bin_buf)将bin_buf二进制数组反转换回buf # 整型数 -> 二进制流 buf1 = 256 bin_buf1 = struct.pack('i', buf1 bin_buf1) print bin_buf1, ' <====> ', ret1 # 浮点数 -> 二进制流 buf2 = 3.1415 bin_buf2 = struct.pack ) print bin_buf2, ' <====> ', ret2 # 字符串 -> 二进制流 buf3 = 'Hello World' bin_buf3 = struct.pack 主要函数 struct模块中最重要的三个函数是pack(), unpack(), calcsize() # 按照给定的格式化字符串,把数据封装成字符串(实际上是类似于c结构体的字节流)string = struct.pack
首先发送要发送的字节总数量 # 然后再发送真实数据 result = str(doSql(sql)).encode('gbk') conn.send(struct.pack result))) conn.send(result) except: message = b'error' conn.send(struct.pack sql.startswith('select'): try: result = str(getData(sql)).encode('gbk') conn.send(struct.pack result))) conn.send(result) except: message = b'error' conn.send(struct.pack 'select', 'delete', 'insert','update')): message = b'not a sql statement' conn.send(struct.pack