[英]python arp header unpacking with struct module
我要制作自己的python嗅探器,但在解壓縮arp協議標頭時遇到問題。
這是我的代碼:
def Sniffer():
try:
# AF_PACKET, That's basically packet level.
# 0X0003, That's every packet. (We can find it here: /usr/include/linux/if_ether.h)
SK = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error as MSG:
print "Socket creation error:\n", MSG
try:
while True:
Receive = SK.recvfrom(65565)
Packet = Receive[0]
Ethernet(Packet)
except socket.error as MSG:
print "Receive error:\n", MSG
# Ethernet Decapsulation (We need EtherType field value)
def Ethernet(Packet):
ETHERNET_LENGTH = 14
ETHERNET_HEADER = Packet[:ETHERNET_LENGTH]
ETHERNET_HEADER_UNPACK = struct.unpack("!6s6sH", ETHERNET_HEADER)
EtherType = ETHERNET_HEADER_UNPACK[2]
print EtherType
if EtherType == 2054:
ARP(ETHERNET_LENGTH, Packet)
if EtherType == 2048:
IPV4(Packet)
# ARP Decapsulation (We need OPCODE field value)
def ARP(ETHERNET_LENGTH, Packet):
ARP_LENGTH = 42
ARP_HEADER = Packet[ETHERNET_LENGTH:ARP_LENGTH]
ARP_HEADER_UNPACK = struct.unpack("!2s2s1s1s2s6s4s6s4s", ARP_HEADER)
OPCODE = ARP_HEADER_UNPACK[4]
if OPCODE == 1:
print "ARP Request (Some one scann your network)"
那是我的錯誤:
Traceback (most recent call last):
File "HoneySniffer.py", line 130, in <module>
Sniffer()
File "HoneySniffer.py", line 22, in Sniffer
Ethernet(Packet)
File "HoneySniffer.py", line 38, in Ethernet
ARP(ETHERNET_LENGTH, Packet)
File "HoneySniffer.py", line 48, in ARP
ARP_HEADER_UNPACK = struct.unpack("!2s2s1s1s2s6s4s6s4s", ARP_HEADER)
struct.error: unpack requires a string argument of length 28
為什么會這樣呢?
我該如何解決?
我在這里找到它: Python arp嗅探原始套接字沒有回復數據包
我有完全相同的問題,我使用您的參考鏈接Python arp嗅探了原始套接字,沒有回復數據包 ,也沒有進行任何研究。
conn=socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.ntohs(0x0003))
def arp_header(packet):
(a ,b ,c ,d ,e ,f ,g ,h ,i ) = struct.unpack('2s2s1s1s2s6s4s6s4s',packet[14:42])
hw_type=(binascii.hexlify(a)).decode('utf-8')
proto_type=(binascii.hexlify(b)).decode('utf-8')
hw_size=(binascii.hexlify(c)).decode('utf-8')
proto_size=(binascii.hexlify(d)).decode('utf-8')
opcode=(binascii.hexlify(e)).decode('utf-8')
return (hw_type,proto_type,hw_size,proto_size,opcode,socket.inet_ntoa(g),socket.inet_ntoa(i))
使用struct.unpack('2s2s1s1s2s6s4s6s4s',packet[14:42])
而不是struct.unpack('!2s2s1s1s2s6s4s6s4s',packet[14:42])
這解決了我的struct.error: unpack requires a string argument of length 28
錯誤
由於我的項目要求,我還使用了各個變量,
現在,為了調試,我使用了print(packet[14:42])
-這給了我字節十六進制的文字(例如b'\\x00\\x01\\x08\\x00\\x06\\x04\\x00\\x01\\xe4\\x11[I&\\xbe\\n\\x00.....
等)
所以我必須在使用hexlify之后在utf-8中解碼,因為hexlify再次將字節對象返回給我。
我使用的Python版本:3.6.5
日期:03 / April / 2019
結果: - Arp Packet: - H/W Type: 0001, Protocol Type: 0800, H/W Size: 06 ,Protocol Size: 04 - Opcode: 0001, Source IP: 10.0.15.141, Destination IP: 10.0.10.2
結論:這種方法對我有用,我希望它也對您有用:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.