2016-01-18 27 views
0

我已經在python中編寫了一個程序,其中將發送一個字節數組以激活汽車網關中的協議功能。基本上我正在構建一個較低級別的ISO-OSI結構,它發送一個以太網層數據包以及ARP協議結構。我通過以太網LAN電纜將Raspberry pi 2連接到網關。我正在Raspberry中使用API​​來運行代碼。我正在使用python 3進行編譯。將以太網數據和ARP協議一起發送到Python的汽車網關

#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) 

當我在我的覆盆子PI

$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. 

我已經盡在谷歌和維基百科級別最適合這種似是而非的錯誤,但無法找到任何。我在Python中只有一個月的時間。所以在這個問題上的任何線索或幫助將是有益的和方便的。

可能的解決方案

由於我使用python 3,它拋出了一個錯誤。在Python 2中,它非常完美。可能在Python 3我不能發送十六進制小數作爲字符串!如果這是問題,有人可以幫助我如何克服這個錯誤。

回答

0

您的pack()函數不起作用,因爲chr函數 返回str但不是字節字符串。有關可能的解決方案,請參閱chr() equivalent returning a bytes object, in py3k

在你的情況,最簡單的解決方法是直接使用bytearray

r = sendeth(bytearray(ethernet_packet), 
     bytearrayarp_packet)) 
+0

我已經用'bytearray'嘗試,但同樣的錯誤拋出了。 – qwerty

+0

@qwerty我重寫了答案。 – jofel