[英]Error unpacking TCP header only some of the time
我正在做一個學校項目,其中涉及讀取數據包。 我需要知道數據包的源和目標IP,協議以及源和目標端口。 現在,我的IP標頭運行良好,但是當我顯示TCP標頭中的端口時,僅在某些時候出現錯誤。 同樣,我想避免使用外部庫和工具,因為我不確定標記后將在哪個環境下測試項目。
錯誤
Traceback (most recent call last):
File "capturePacket.py", line 26, in <module>
tcp_hdr = struct.unpack("!HHII2sH2sH", tcpheader)
struct.error: unpack requires a buffer of 20 bytes
一些指導會有所幫助。 謝謝。
import socket,struct,binascii,os
#if windows
if os.name == "nt":
s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)
s.bind((socket.gethostname(),0))
s.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
s.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)
#if other
else:
s=socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800))
while True:
pkt=s.recvfrom(65565)
print ("\n\nIP Header:")
ipheader = pkt[0][14:34]
ip_hdr = struct.unpack("!1s1s1H1H2s1B1B2s4s4s",ipheader)
print ("Source IP", socket.inet_ntoa(ip_hdr[8]))
print ("Destination IP", socket.inet_ntoa(ip_hdr[9]))
print ("Protocol", ip_hdr[6])
print ("\n\nTCP Header:")
tcpheader = pkt[0][34:54]
tcp_hdr = struct.unpack("!HHII2sH2sH", tcpheader)
print ("Source Port:", tcp_hdr[0])
print ("Destination Port:", tcp_hdr[1])
這個問題非常簡單。 您既沒有將BPF過濾器傳遞給嗅探器,以僅將數據包捕獲限制為TCP,也沒有檢查IP協議值實際上是6還是TCP。
這一切的意思是,當您隨后嘗試解壓縮假定為TCP標頭的數據包時,可能會發現在UDP或ICMP數據包(當然是某些其他嵌入式協議)中的數據要少得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.