Search code examples
pythonsocketsudpsniffer

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


Solution

  • 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)