本文整理匯總了Python中struct.pack方法的典型用法代碼示例。如果您正苦於以下問題:Python struct.pack方法的具體用法?Python struct.pack怎麽用?Python struct.pack使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類struct
的用法示例。
在下文中一共展示了struct.pack方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def __init__(self, path, mode):
assert mode in ("r", "w")
self.path = path
self.file = open(self.path, mode + "b")
self.mmfile = None
self.mode = mode
self.cnt = _CacheFileContent()
if mode == "r":
# Read the last part of the file which contains the contents of the
# cache.
self.cnt.read(self.file, self.path)
self.mmfile = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_READ)
else:
# The 8 bytes header contain the position of the content index.
# We fill this header with zeroes and write the actual position
# once all samples have been written to the cache
self.file.write(struct.pack('<Q', 0))
示例2: fuzz
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def fuzz(self, fuzzer):
"""Return a fuzzed version of this page."""
# TODO, for these vorbis header pages, should fuzz the parameters within structures
# https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-600004.2
#print "fuzz",
if self.special == b"\x01vorbis":
#print "spc1",
hdr = self.fuzz_header(fuzzer)
vorbhdr = bytes(fuzzer(self.data[0][7:])[:22])
data = [b"".join([b"\x01vorbis", vorbhdr, b"\x01" * (23 - len(vorbhdr))])]
elif self.special: # unknown "special" page
#print "spcx (k)"
return b"".join([self.header] + self.data)
else:
#print "nspc",
hdr = self.fuzz_header(fuzzer)
data = [bytes(fuzzer(i)[:255]) for i in self.data[:255]]
out = b"".join([hdr, bytes([len(data)])] + [bytes([len(i)]) for i in data] + data)
pagecrc = ogg_crc32(out)
out = b"".join([out[:22], struct.pack("<I", pagecrc), out[26:]])
#print "ok"
return out
示例3: ZapMBRGPT
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def ZapMBRGPT(self, disk_size, sector_size, add1MB):
self.assert_physical_drive()
# Implementation borrowed from rufus: https://github.com/pbatard/rufus
num_sectors_to_clear \
= (add1MB and 2048 or 0) + self.MAX_SECTORS_TO_CLEAR
zeroBuf = b'\0' * sector_size
for i in range(num_sectors_to_clear):
self.WriteFile(zeroBuf)
offset = disk_size - self.MAX_SECTORS_TO_CLEAR * sector_size
win32file.SetFilePointer(self.h, offset, win32con.FILE_BEGIN)
for i in range(num_sectors_to_clear):
self.WriteFile(zeroBuf)
# We need to append paddings as CREATE_DISK structure contains a union.
param = struct.pack('<IIIHH8s',
winioctlcon.PARTITION_STYLE_MBR, 0xdeadbeef,
0,0,0,b'abcdefgh')
win32file.DeviceIoControl(
self.h, winioctlcon.IOCTL_DISK_CREATE_DISK, param, 0, None)
示例4: run
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def run(self):
while True:
try:
self.sock.connect(self.ADDR)
break
except:
time.sleep(3)
continue
print("AUDIO client connected...")
self.stream = self.p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while self.stream.is_active():
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = self.stream.read(CHUNK)
frames.append(data)
senddata = pickle.dumps(frames)
try:
self.sock.sendall(struct.pack("L", len(senddata)) + senddata)
except:
break
示例5: hciCallback
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def hciCallback(self, record):
hcipkt, orig_len, inc_len, flags, drops, recvtime = record
dummy = "\x00\x00\x00" # TODO: Figure out purpose of these fields
direction = p8(flags & 0x01)
packet = dummy + direction + hcipkt.getRaw()
length = len(packet)
ts_sec = recvtime.second #+ timestamp.minute*60 + timestamp.hour*60*60 #FIXME timestamp not set
ts_usec = recvtime.microsecond
pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
try:
self.wireshark_process.stdin.write(pcap_packet)
self.wireshark_process.stdin.flush()
log.debug("HciMonitorController._callback: done")
except IOError as e:
log.warn("HciMonitorController._callback: broken pipe. terminate.")
self.killMonitor()
示例6: lmpCallback
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def lmpCallback(self, lmp_packet, sendByOwnDevice, src, dest, timestamp):
eth_header = dest + src + "\xff\xf0"
meta_data = "\x00"*6 if sendByOwnDevice else "\x01\x00\x00\x00\x00\x00"
packet_header = "\x19\x00\x00" + p8(len(lmp_packet)<<3 | 7)
packet = eth_header + meta_data + packet_header + lmp_packet
packet += "\x00\x00" # CRC
length = len(packet)
ts_sec = timestamp.second + timestamp.minute*60 + timestamp.hour*60*60
ts_usec = timestamp.microsecond
pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
try:
self.wireshark_process.stdin.write(pcap_packet)
self.wireshark_process.stdin.flush()
log.debug("LmpMonitorController._callback: done")
except IOError as e:
log.warn("LmpMonitorController._callback: broken pipe. terminate.")
self.killMonitor()
示例7: send
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def send(self, channel_type, message, additional_data):
if channel_type == common.CONTROL_CHANNEL_BYTE:
transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
else:
transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)
common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)
# WORKAROUND?!
# Windows: It looks like when the buffer fills up the OS does not do
# congestion control, instead throws and exception/returns with
# WSAEWOULDBLOCK which means that we need to try it again later.
# So we sleep 100ms and hope that the buffer has more space for us.
# If it does then it sends the data, otherwise tries it in an infinite
# loop...
while True:
try:
return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
except socket.error as se:
if se.args[0] == 10035: # WSAEWOULDBLOCK
time.sleep(0.1)
pass
else:
raise
示例8: cmh_autotune
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def cmh_autotune(self, module, message, additional_data, cm):
message = message[len(self.CONTROL_AUTOTUNE)+2:]
# get tune type, requested record type, length and encoding for crafting the answer
(query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7])
if self.DNS_proto.get_RR_type(RRtype)[0] == None:
return True
# extra parameters added to be able to response in the proper way
additional_data = additional_data + (True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0])
if (query_type == 0) or (query_type == 3):
# record && downstream length discovery
message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
if query_type == 1:
# A record name length discovery
message = struct.pack("<i", binascii.crc32(message[7:]))
if query_type == 2:
# checking download encoding, echoing back request payload
message = message[7:]
module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT+message, additional_data)
return True
# tune control message handler
# client sets the record type and encodings by calling this
# server side
示例9: do_changesettings
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def do_changesettings(self, additional_data):
message = struct.pack("<HHHH", self.settings[4], self.settings[0], self.settings[1], self.settings[3])
self.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_TUNEME+message, additional_data)
if (self.record_list[self.settings[4]][0] == "CNAME"):
self.recordtype = self.settings[5]
else:
self.recordtype = self.record_list[self.settings[4]][0]
self.RRtype_num = self.DNS_proto.reverse_RR_type_num(self.recordtype)
self.upload_encoding_class = self.upload_encoding_list[self.settings[0]]
self.download_encoding_class = self.download_encoding_list[self.settings[1]]
self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](self.settings[2]-1, self.hostname, 3, self.upload_encoding_class)
self.set_mtu_ugly(self.DNS_proto.reverse_RR_type(self.recordtype)[4](self.settings[3]-1, "", 3, self.download_encoding_class))
return
# function used for autotuning, crafting tune type requests, sending the
# packets then checking the answer.
# return
# True: if the packet went thru and the answer is correct. Encoding, size
# were correct
# False: packet failed. Too big or crippled packet, wrong encoding etc.
示例10: decode
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def decode(self, text):
if len(text) % 5:
return None
decoded_text = ""
text = text.replace("{",".")
for i in range(0, len(text)/5):
encoded_text = text[i*5:(i+1)*5]
N0 = ord(encoded_text[0]) - 33
N1 = ord(encoded_text[1]) - 33
N2 = ord(encoded_text[2]) - 33
N3 = ord(encoded_text[3]) - 33
N4 = ord(encoded_text[4]) - 33
c = N0*52200625 + N1*614125 + N2*7225 + N3*85 + N4
decoded_text += struct.pack(">I", c)
return decoded_text
示例11: build_answer
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def build_answer(self, transaction_id, record, orig_question):
if record == None:
flag = 0x8503 # 1000 0100 0000 0011
answer_num = 0
answers = ""
additional_record_num = 0
additional_records = ""
else:
flag = 0x8500 # 1000 0100 0000 0000
RRtype = self.reverse_RR_type(record[0])
if RRtype[1] == None:
answer_num = 0
answers = ""
additional_record_num = 0
additional_records = ""
else:
answer_num = 1
(answer_num, answers, additional_record_num, additional_records) = RRtype[1](record)
dns_header = struct.pack(">HHHHHH", transaction_id, flag, 1, answer_num, 0, additional_record_num)
return dns_header + orig_question + answers + additional_records
示例12: freebsd_tun_alloc
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def freebsd_tun_alloc(self, dev, flags):
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ifr = struct.pack('<16si', 'tun', 0)
self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
self.iface_name = self.iface_name.rstrip("\x00")
buff = array.array('c', dev+"\x00")
caddr_t, _ = buff.buffer_info()
ifr = struct.pack('16sP', self.iface_name, caddr_t);
fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
self.iface_name = dev
except IOError as e:
print e
common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
sys.exit(-1)
return tun
示例13: pack
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
raise ValueError("Invalid packed data length for field %s of %d "
"does not fit field size of %d"
% (self.name, len(packed_value), size))
return packed_value
示例14: __init__
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def __init__(self, size=None, **kwargs):
"""
[MS-DTYP] 0.0 2017-09-15
2.3.3 FILETIME
The FILETIME structure is a 64-it value that represents the number of
100 nanoseconds intervals that have elapsed since January 1, 1601 UTC.
This is used to convert the FILETIME int value to a native Python
datetime object.
While the format FILETIME is used when communicating with the server,
this type allows Python code to interact with datetime objects natively
with all the conversions handled at pack/unpack time.
:param size: Must be set to None or 8, this is so we can check/override
:param kwargs: Any other kwarg to be sent to Field()
"""
if not (size is None or size == 8):
raise InvalidFieldDefinition("DateTimeField type must have a size "
"of 8 not %d" % size)
super(DateTimeField, self).__init__(size=8, **kwargs)
示例15: __new__
# 需要導入模塊: import struct [as 別名]
# 或者: from struct import pack [as 別名]
def __new__(cls, *args, **kwargs):
if cls.__instance == None or (len(args) > 0 and args[0] == 'reset'):
cls.__instance = object.__new__(cls)
cls.__instance.name = "IpmiServer Context"
# Initialize ctx state
self = cls.__instance
self.device_name = "CloudStack IPMI Sim"
self.sessions = dict()
self.uuid = uuid.uuid4()
self.kg = None
self.authdata = collections.OrderedDict()
lanchannel = 1
authtype = 0b10000000
authstatus = 0b00000100
chancap = 0b00000010
oemdata = (0, 0, 0, 0)
self.authcap = struct.pack('BBBBBBBBB', 0, lanchannel, authtype, authstatus, chancap, *oemdata)
self.bmc = self._configure_users()
logger.info('CloudStack IPMI Sim BMC initialized')
return cls.__instance