我目前的任务是剖析包含 P2P 消息的 tcpdump 数据,我在获取和写入 x86 机器上的文件的片段数据时遇到了问题。我怀疑我写入文件的字节有一个简单的字节顺序问题。
我有一个字节列表,其中包含一段使用 python-pcapy 包 BTW 读取和处理的 P2P 视频。
bytes = [14, 254, 23, 35, 34, 67, etc...]
我正在寻找一种方法来存储这些字节,这些字节目前保存在我的 Python 应用程序的列表中到一个文件中。
目前我写的片段如下:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"ab")
# Iterate through bytes writing them to a file if don't have piece already
if not self.piecemap[ipdst].has_key(pieceindex):
for byte in bytes:
file.write('%c' % byte)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
# TODO: Collect stats
file.close()
正如您从 for 循环中看到的那样,我将字节写入文件的顺序与我从线路中处理它们的顺序相同(即网络顺序或大端顺序)。
可以这么说,作为片段有效载荷的视频在 VLC 中播放效果不佳 :-D
我想我需要将它们转换为小端字节顺序,但不确定在 Python 中实现此目的的最佳方法。
更新
为我解决的解决方案(编写 P2P 片段适本地处理字节序问题)是:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"r+b")
if not self.piecemap[ipdst].has_key(pieceindex):
little = struct.pack('<'+'B'*len(bytes), *bytes)
# Seek to offset based on piece index
file.seek(pieceindex * self.piecesize)
file.write(little)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
file.close()
解决方案的关键是怀疑使用 Python struct 模块,特别是:
little = struct.pack('<'+'B'*len(bytes), *bytes)
感谢那些提供有用建议的人。
最佳答案
为了节省一些工作,您可能喜欢使用 bytearray
(Python 2.6 及更高版本):
b = [14, 254, 23, 35]
f = open("file", 'ab')
f.write(bytearray(b))
这会将您的 0-255 值全部转换为字节,而无需所有循环。
如果没有更多信息,我看不出你的问题是什么。如果数据确实是按字节排列的,那么字节顺序就不是问题,正如其他人所说。
(顺便说一句,使用 bytes
和 file
作为变量名并不好,因为它隐藏了同名的内置函数)。
关于将网络字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405972/