Shatnerz
Shatnerz

Reputation: 2543

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

Upvotes: 2

Views: 2801

Answers (2)

imreal
imreal

Reputation: 10358

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)

Upvotes: 2

user_ABCD
user_ABCD

Reputation: 347

No matter the packet sniffer you are using (whether it be wireshark or tcpdump), you can set packet filters to select a specific port. i.e. (tcpdump port port #) or (udp.port == port #).

Upvotes: 0

Related Questions