Python 3.4 very simple packet sniffer

850 views Asked by At

How can I make packet sniffer at selected server and port? Something like Wpe Pro or RPE, but I want to use Python and 'print' for writing these packets. I tried this:

import socket

UDP_IP = "xx.xx.xx.xx"
UDP_PORT = xxxx

sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print("received message:", data)

but I think it can't work (UDP or something else is wrong?). How can I do it correctly?

2

There are 2 answers

0
robert On

I have working code that sends then receives and it goes a little something like this:

# set up the UDP socket
connection = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection.settimeout(5)

# Send packet by UDP
connection.sendto(request_bytes, (UDP_IP, UDP_PORT))

# Receive response packet
response_bytes = connection.recv(4096)

Could it be the case that settimeout is missing for you?

0
fferri On

pypcap is a simplified object-oriented Python wrapper for libpcap - the current tcpdump.org version, and the WinPcap port for Windows.

That might save you some time.