0
저는 패킷을 읽는 것을 포함하는 학교 프로젝트 작업을하고 있습니다. 패킷의 출발지 및 목적지 IP, 프로토콜 및 출발지 및 목적지 포트를 알아야합니다. 지금은 IP 헤더가 잘 실행되고 있지만 TCP 헤더에서 포트를 표시 할 때 오류가 발생합니다. 또한 필자는 외부 라이브러리와 도구를 사용하지 말고 표시 할 때 어떤 환경에서 프로젝트를 테스트 할 지 확신하지 못합니다.일부 시간에만 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])