gpt4 book ai didi

python - 如何使用 Python 3.3 实现原始帧捕获?

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:57 25 4
gpt4 key购买 nike

注意:我不确定这是编程问题还是特定于硬件/操作系统的相关问题。

我正在尝试使用 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] Address family not supported by protocol.

在此特定行处中断:

s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)

我对代码所做的唯一更改是实际的接口(interface)名称(即“em1”)。我使用的是 Fedora 15。

进一步查看 Python 源代码,似乎发现 AF_CAN(地址族)和 CAN_RAW(协议(protocol))不是正确的对。

如何捕获原始以太网帧以进行进一步处理?

<小时/>

最终我需要做的是捕获原始以太网帧并在其进入​​系统时对其进行处理。

最佳答案

我终于能够通过以下方式做到这一点:

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

关于python - 如何使用 Python 3.3 实现原始帧捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20339377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com