python
复制代码
from scapy.all import *
from scapy.layers.inet import UDP, IP
from scapy.layers.l2 import Ether
def Callback(packet):
# 目的IP
dst_ip = packet[IP].dst
# 源IP
src_ip = packet[IP].src
# 目的端口
dst_port = packet[UDP].dport
# 数据
value = packet['Raw'].load
# 目的MAC地址
dst_mac = packet['Ether'].dst
# 源MAC地址
src_mac = packet['Ether'].src
print(f"收:{packet}")
# 转发数据
forward_udp(dst_mac, src_mac, dst_ip, src_ip, dst_port, value)
def forward_udp(dst_mac, src_mac, dst_ip, src_ip, dst_port, value):
"""
转发数据至指定目标
:param dst_mac: 目的MAC
:param src_mac: 源MAC
:param dst_ip: 目的IP
:param src_ip: 源IP
:param dst_port: 目的端口
:param value: 数据
:return:
"""
# 创建以太网层
eth = Ether(dst=dst_mac, src=src_mac)
# 创建IP层
ip = IP(src=src_ip, dst=dst_ip)
# 创建UDP层
udp = UDP(dport=dst_port + 1)
# 创建一个UDP数据包
packet = eth / ip / udp / Raw(value)
print(f"发:{packet}")
# 通过原始套接字发送数据包,iface:指定网卡名称
sendp(packet, iface="WLAN")
if __name__ == '__main__':
# 目标地址
IP = '192.168.3.1'
# 目标端口
Port = '9999'
# 监听的规则,iface:监听的网卡名称
sniff(filter=f"udp and host {IP} and port {Port}", iface="WLAN", count=-1, prn=Callback)