发送端程序(sender.py):
from scapy.all import send, IP, TCP
source_ip = "192.168.42.232"
target_ip = "192.168.42.45"
send_port = 8888
msg = "hello, world"
packet = IP(src=source_ip, dst=target_ip) / TCP(sport=send_port, dport=6666) / msg
send(packet, iface="Intel(R) Dual Band Wireless-AC 8260") # 显式指定使用的网卡适配器进行发送
接收端程序(receiver.py):
from scapy.all import sniff, TCP
receive_port = 6666
def packet_handler(packet):
if TCP in packet and packet[TCP].dport == receive_port:
packet.show()
sniff(filter=f"tcp port {receive_port}", prn=packet_handler)
请注意,与使用 UDP 协议的示例代码相比,这里将 UDP
对象替换为了 TCP
对象,同时将过滤器中的 udp
替换为 tcp
。并将源ip地址,目标ip地址修改为本机和目标地址的ip地址。
参考运行方式与之前相同:
- 打开一个终端,运行接收端程序:
python receiver.py
- 打开另一个终端,运行发送端程序:
python sender.py
发送端程序发送数据包后,接收端程序会监听指定的端口,并打印输出接收到的内容。
请确保发送端和接收端程序的运行环境正确配置,并且确保防火墙设置不会阻止端口之间的通信。