使用括号进行字节切片以解压缩

时间:2019-07-15 09:18:19

标签: python network-programming pcapy

我正在尝试对包含多个字节的变量进行切片,因此可以将unpack与14个字节的缓冲区一起使用。但是显然它没有用。我在这里做什么错了?

import pcapy
from struct import *
import sys

devs = pcapy.findalldevs()

cap = pcapy.open_live(devs[4], 65535, 0, 1)

while 1:
    (header, payload) = cap.next()
    print(sys.getsizeof(payload))
    l2hdr = payload[:14]
    print(sys.getsizeof(l2hdr))
    l2data = unpack("!6s6sH", l2hdr)
    srcmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (l2hdr[0]), (l2hdr[1]), (l2hdr[2]), (l2hdr[3]), (l2hdr[4]), (l2hdr[5])
    dstmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (l2hdr[6]), (l2hdr[7]), (l2hdr[8]), (l2hdr[9]), (l2hdr[10]), (l2hdr[11])
    print("Source MAC: ", srcmac, " Destination MAC: ", dstmac)

这是结果

Traceback (most recent call last):
  File "C:/Users/admin/Downloads/test1.py", line 14, in <module>
    l2data = unpack("!6s6sH", l2hdr)
17
struct.error: unpack requires a buffer of 14 bytes
17

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

我怀疑您的有效载荷为空。 17个字节太小。

如果检查有效载荷和/或标头的len,则应大于0。

将其用作测试以查看是否有任何数据。

while 1:
    (header, payload) = cap.next()
    while len(payload) == 0:
        (header, payload) = cap.next()

尽管这现在在其余代码中显示了一个错误。

Traceback (most recent call last):
  File "go.py", line 18, in <module>
    srcmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (l2hdr[0]), (l2hdr[1]), (l2hdr[2]), (l2hdr[3]), (l2hdr[4]), (l2hdr[5])
TypeError: not enough arguments for format string

我用fstrings把你的原作改写了,效果很好

import pcapy
from struct import unpack

devs = pcapy.findalldevs()

cap = pcapy.open_live(devs[4], 65535, 0, 1)

while 1:
    (header, payload) = cap.next()
    while len(payload) == 0:
        (header, payload) = cap.next()
    l2hdr = payload[:14]
    l2data = unpack("!6s6sH", l2hdr)
    srcmac = f"{l2hdr[0]:2x}:{l2hdr[1]:2x}:{l2hdr[2]:2x}:{l2hdr[3]:2x}:{l2hdr[4]:2x}:{l2hdr[5]:2x}"
    dstmac = f"{l2hdr[6]:2x}:{l2hdr[7]:2x}:{l2hdr[8]:2x}:{l2hdr[9]:2x}:{l2hdr[10]:2x}:{l2hdr[11]:2x}"
    print("Source MAC: ", srcmac, " Destination MAC: ", dstmac)