Python是一種高級編程語言,常常用于網絡編程。本文將介紹如何使用Python監聽數據包。
# 導入所需模塊 import socket import struct # 定義IP頭格式 ip_header = struct.Struct('!BBHHHBBH4s4s') def parse_ip_header(data): """解析IP頭""" version_header_length, tos, total_length, id_, flags_offset, ttl, protocol, checksum, source_address, dest_address = ip_header.unpack(data[:20]) version = version_header_length >>4 header_length = (version_header_length & 0xF) * 4 return version, header_length, ttl, protocol, source_address, dest_address, data[header_length:total_length] # 定義TCP頭格式 tcp_header = struct.Struct('!HHLLBBHHH') def parse_tcp_header(data): """解析TCP頭""" source_port, dest_port, seq_num, ack_num, offset_reserved_flags, window_size, checksum, urgent_pointer = tcp_header.unpack(data[:20]) offset = (offset_reserved_flags >>4) * 4 flags = offset_reserved_flags & 0xF return source_port, dest_port, seq_num, ack_num, flags, window_size, data[offset:] # 創建套接字并監聽 HOST = '127.0.0.1' PORT = 8888 with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) as s: s.bind((HOST, PORT)) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) while True: data, addr = s.recvfrom(65535) version, header_length, ttl, protocol, source_address, dest_address, payload = parse_ip_header(data) if protocol == socket.IPPROTO_TCP: source_port, dest_port, seq_num, ack_num, flags, window_size, tcp_payload = parse_tcp_header(payload) print(f'source_address: {source_address}, source_port: {source_port}, dest_address: {dest_address}, dest_port: {dest_port}, flags: {flags}, tcp_payload: {tcp_payload}')
以上代碼通過創建原始套接字,并監聽TCP數據包,解析IP頭和TCP頭,輸出相關信息。
上一篇java輸入m和m