简体   繁体   English

侦听python中已用于UDP数据包的端口吗?

[英]Listen to a port already in use for UDP packets in python?

Essentially I have a program, A, send results (just data points) in real time to another program, B, to handle. 本质上,我有一个程序A,可以将结果(只是数据点)实时发送到另一个程序B中进行处理。 Each data point is sent as a UDP packet, on a specific port and 127.0.0.1, containing the point as a string. 每个数据点都作为UDP数据包在特定端口和127.0.0.1上发送,其中包含该点作为字符串。 When B is not running, I can just do 当B不运行时,我可以做

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1, port))
while True:
    data, addr = sock.recvfrom(65565)

And then obviously when B is running, I get 然后很明显,当B运行时,我得到

[Errno 98] Address already in use

How can I see the packets sent on these ports? 如何查看在这些端口上发送的数据包? In the past (separate project) I had a packet sniffer using 过去(单独的项目)我使用了一个数据包嗅探器

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

which saw all incoming and outgoing UDP packets, but that seems excessive. 可以看到所有传入和传出的UDP数据包,但这似乎过多。 I only need to see the packets from a specific port. 我只需要查看来自特定端口的数据包。 I'm fairly new to this lower level socket programming. 我对这个较低级别的套接字编程还很陌生。 Any help is appreciated 任何帮助表示赞赏

You can use scapy : 您可以使用scapy

This is a small example: 这是一个小例子:

from scapy.all import *

def callback(pkt):
    pkt.show()

sniff(prn=callback, filter="tcp and ( port 25 or port 110)

No matter the packet sniffer you are using (whether it be wireshark or tcpdump), you can set packet filters to select a specific port. 无论您使用的是哪种数据包嗅探器(无论是wireshark还是tcpdump),都可以设置数据包过滤器以选择特定的端口。 ie (tcpdump port port #) or (udp.port == port #). 即(tcpdump端口端口号)或(udp.port ==端口号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM