Reputation: 19
I'm trying to slice a variable containing a number of bytes, so I can use unpack with a buffer of 14 bytes. But apparently it's not working. What am I doing wrong here?
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)
and here's the result
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
Upvotes: 1
Views: 242
Reputation: 956
I suspect your payload is empty. The 17 bytes is too small.
If you check the len of the payload and/or header, it should be greater than 0.
Use that as a test to see if you have any data.
while 1:
(header, payload) = cap.next()
while len(payload) == 0:
(header, payload) = cap.next()
Though that's now showing an error in the rest of your code.
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
I rewrote your original to this with fstrings and it's working well
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)
Upvotes: 0