来自客户端-服务器 (udp) 连接的数据包嗅探器 python 2.7(仅)

packets sniffer from client-server(udp) connection python 2.7 (only)

我编写了向服务器发送数据包的客户端,现在我需要创建一个对手来监听(在本地主机上)客户端和服务器之间的连接,并打印数据包内容,对手不是连接。我遇到了一些问题,我知道我需要使用原始套接字,但我不知道为什么我不能这样做。

服务器:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 12321)
print >> sys.stderr, 'starting up on localhost port 12321'
sock.bind(server_address)

while True:
    data, address = sock.recvfrom(100)
    if data:
        sent = sock.sendto(data, address)
        print >> sys.stderr, 'sent %s bytes back to %s' % (sent, address)

客户:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 12321)
i = 0

    while True:
        f = open("poem.txt", "r")
        for line in f:
            time.sleep(3)
            i += 1
            sent = sock.sendto(line, server_address)
            data, server = sock.recvfrom(100)
        f.close()

    print >>sys.stderr, 'closing socket'
    sock.close()

对手:

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s.bind(("localhost", 1))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while True:
   print s.recvfrom(12321)

在对手中,我收到了各种消息,但没有收到客户端发送的消息(客户端发送了一首歌)。请帮助...

问题出在你的绑定上, socket.bind() 接受地址元组 (IP,PORT)

您的客户端绑定到端口 12321,但您的对手设置为端口 1

s.bind(("localhost", 1)) #change 1 to 12321

此外,socket.recvfrom() 获取缓冲区大小作为参数而不是端口。

   print s.recvfrom(12321) #change to buffer size

查看套接字文档: https://docs.python.org/2/library/socket.html

另外,我可以建议使用 Scapy 工具, Windows 和 Linux

都很容易使用

只需在命令中输入 pip install scapy 然后 在 windows 上确保你在 scapy 中安装了 npcap https://nmap.org/npcap/windows-10.html 你准备好了

安装 scapy 之后你只需要这样一行:

sniff(filter="udp and host 127.0.0.1 and dst port 12321", prn=lambda x:x.sprintf("{IP:%IP.src% -> %IP.dst%\n}{Raw:%Raw.load%\n}"))