简体   繁体   English

仅在某些时间错误解压缩TCP标头

[英]Error unpacking TCP header only some of the time

I am working on a school project which involves reading in packets. 我正在做一个学校项目,其中涉及读取数据包。 I'm required to know the packet's source and destination IP, protocol, and source and destination ports. 我需要知道数据包的源和目标IP,协议以及源和目标端口。 Right now I have the IP header running well, but when I display the ports from the TCP header I receive an error only some of the time. 现在,我的IP标头运行良好,但是当我显示TCP标头中的端口时,仅在某些时候出现错误。 As well I would like to refrain from using external libraries and tools as I am not sure what environment the project will be tested on when marked. 同样,我想避免使用外部库和工具,因为我不确定标记后将在哪个环境下测试项目。

The error 错误

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

Some guidance would be helpful. 一些指导会有所帮助。 Thank you. 谢谢。

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

The problem is very straightforward; 这个问题非常简单。 you are neither passing a BPF filter to the sniffer to limit your packet capture to TCP only, nor are you checking to see if the IP protocol value is, in fact, 6 or TCP. 您既没有将BPF过滤器传递给嗅探器,以仅将数据包捕获限制为TCP,也没有检查IP协议值实际上是6还是TCP。

What all of this means is that when you then go to try to unpack what you are assuming will be a TCP header, you may instead be finding far less data in a UDP or ICMP packet (or some other embedded protocol, of course). 这一切的意思是,当您随后尝试解压缩假定为TCP标头的数据包时,可能会发现在UDP或ICMP数据包(当然是某些其他嵌入式协议)中的数据要少得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM