interface = "eth0" # 替换为实际的网络接口名
capture = pcap.pcap(name=interface)
for timestamp, packet in capture:
print(timestamp, packet)
def decode_ethernet_packet(packet):
ethernet_header = packet[:14] # 以太网头部长度为14字节
destination_mac = ":".join("{:02x}".format(ord(c)) for c in ethernet_header[:6])
source_mac = ":".join("{:02x}".format(ord(c)) for c in ethernet_header[6:12])
ether_type = (ord(ethernet_header[12]) << 8) + ord(ethernet_header[13])
return{
"destination_mac": destination_mac,
"source_mac": source_mac,
"ether_type": ether_type
}
def decode_ip_packet(packet):
ip_header = packet[14:34] # IP头部长度为20字节
version = ord(ip_header[0]) >> 4
header_length = (ord(ip_header[0]) & 0x0F) * 4
ttl = ord(ip_header[8])
protocol = ord(ip_header[9])
source_ip = ".".join(str(ord(c)) for c in ip_header[12:16])
destination_ip = ".".join(str(ord(c)) for c in ip_header[16:20])
return {
"version": version,
"header_length": header_length,
"ttl": ttl,
"protocol": protocol,
"source_ip": source_ip,
"destination_ip": destination_ip
}
def decode_tcp_packet(packet):
tcp_header = packet[34:54] # TCP头部长度为20字节
source_port = (ord(tcp_header[0]) << 8) + ord(tcp_header[1])
destination_port = (ord(tcp_header[2]) << 8) + ord(tcp_header[3])
return {
"source_port": source_port,
"destination_port": destination_port
}
# 在捕获数据包的循环中调用解析函数
for timestamp, packet in capture:
ethernet_info = decode_ethernet_packet(packet)
ip_info = decode_ip_packet(packet)
tcp_info = decode_tcp_packet(packet)
print("Ethernet Info:", ethernet_info)
print("IP Info:", ip_info)
print("TCP Info:", tcp_info)
print()