我已经在 python 中编程,其中将发送一个字节数组以激活汽车网关中的协议(protocol)功能。基本上我正在构建一个较低级别的 ISO-OSI 结构,它发送一个以太网层的数据包以及 ARP 协议(protocol)结构。我已通过以太网 LAN 电缆将 Raspberry pi 2 连接到网关。我在 Raspberry 中使用 API 来运行代码。我正在使用python 3进行编译。
#start of program
from socket import *
def sendeth(ethernet_packet,payload,interface = "eth0"):
"""Sending RAW Ethernet packets with ARP protocol."""
s= socket(AF_PACKET, SOCK_RAW)
s.bind((interface,0))
return s.send(ethernet_packet + payload)
def pack(byte_sequence):
"""convert list of bytes to byte string"""
return b"".join(map(chr, byte_sequence))
if __name__ == "__main__":
#desadd,srcadd,ethtype
ethernet_packet= [0x00, 0x36, 0xf8, 0x00, 0x5b, 0xed, 0xb8, 0x27, 0xcb, 0x8c, 0x1c, 0xf9, 0x08, 0x06]
#arpprotocol
arp_packet = [0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01, 0xf0, 0x1f, 0xaf, 0x57, 0x33, 0xb1, 0xa9, 0xfe, 0x00, 0x14, 0x00, 0x36, 0xf8, 0x00, 0x5b, 0xed, 0xa9, 0xfe, 0x3f, 0x29]
payload = "".join(map(chr, arp_packet))
r = sendeth(pack(ethernet_packet),
pack(arp_packet))
printf("sent Etherent with ARP_Paket payload length is %d bytes" % r)
当我在我的树莓派中运行程序时
$sudo python3 APR.py
它抛出一个错误,
Traceback (most recent call test):
File"APR.py", line 24,in <module>
r = sendeth(pack(ethernet_packet),
File"APR.py", line 13,in pack
return b"".join(map(chr, byte_sequence))
TypeError: sequence intem 0: expected Bytes, bytearray, or an object with the buffer Interface, str found.
对于这个似是而非的错误,我在 Google 和 Wikipedia 中尝试了我的级别,但找不到任何错误。我刚学 Python 一个月。因此,有关此问题的任何线索或帮助都会有所帮助和方便。
可能的解决方案
由于我使用的是 python 3,因此会引发错误。就像在 Python 2 中一样,它完美无缺。可能在python 3中我无法将十六进制作为字符串发送!如果这是问题,有人可以帮助我如何克服错误。
最佳答案
您的 pack() 函数不起作用,因为 chr
功能
返回 str
但不是字节串。见 chr() equivalent returning a bytes object, in py3k寻找可能的解决方案。
在您的情况下,最简单的解决方案是使用 bytearray
直接地:
r = sendeth(bytearray(ethernet_packet),
bytearrayarp_packet))
关于python - 在 Python 中将以太网数据与 ARP 协议(protocol)一起发送到汽车网关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860510/