注意:我不确定这是编程问题,还是与硬件/操作系统相关的问题。
我尝试使用Python 3.3的套接字类捕获原始以太网帧。直接查看PyDoc's website:
中的示例import socket
import struct
# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)
can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)
def build_can_frame(can_id, data):
can_dlc = len(data)
data = data.ljust(8, b'\x00')
return struct.pack(can_frame_fmt, can_id, can_dlc, data)
def dissect_can_frame(frame):
can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
# create a raw socket and bind it to the 'vcan0' interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(('vcan0',))
while True:
cf, addr = s.recvfrom(can_frame_size)
print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
try:
s.send(cf)
except OSError:
print('Error sending CAN frame')
try:
s.send(build_can_frame(0x01, b'\x01\x02\x03'))
except OSError:
print('Error sending CAN frame')
我收到以下错误:
OSError:[Errno 97]协议不支持地址族。
打破这个特定的行:
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
我对代码所做的唯一更改是实际的界面名称(即&#39; em1&#39;)。我正在使用Fedora 15。
进一步查看Python源代码 ,AF_CAN(地址族)和CAN_RAW(协议)不是正确的对。
如何捕获原始以太网帧以进行进一步处理?
最终我需要做的是捕获原始以太网帧并在进入系统时对其进行处理。
答案 0 :(得分:0)
我终于能够通过以下方式做到这一点:
import socket
import struct
import time
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
test = []
while(1):
now = time.time()
message = s.recv(4096)
# Process the message from here