- 使用Python的第三方库pcapy和dpkt
import pcapy
import dpkt
def packet_handler(header, packet):
    eth = dpkt.ethernet.Ethernet(packet)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        return
    
    ip = eth.data
    src_ip = pcapy.ntoa(ip.src)
    dst_ip = pcapy.ntoa(ip.dst)
    print('Source IP: {}, Destination IP: {}'.format(src_ip, dst_ip))
dev = "eth0"
pcap = pcapy.open_live(dev, 65536, 1, 0)
pcap.setfilter('ip')  # 设置捕获过滤规则
pcap.loop(-1, packet_handler)  # 抓取数据包并处理
- 使用Python的第三方库Scapy
from scapy.all import *
def packet_handler(packet):
    if IP in packet:
        src_ip = packet[IP].src
        dst_ip = packet[IP].dst
        print('Source IP: {}, Destination IP: {}'.format(src_ip, dst_ip))
sniff(filter="ip", prn=packet_handler)  # 抓取符合过滤规则的数据包,并执行处理函数