简体   繁体   中英

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. Each data point is sent as a UDP packet, on a specific port and 127.0.0.1, containing the point as a string. When B is not running, I can just do

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

[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. 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 :

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. ie (tcpdump port port #) or (udp.port == port #).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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