Obi Wan
Obi Wan

Reputation: 149

How to capture UDP packets with Python

Facts & context elements:
I need to capture data (latitude,longitude) coming out of a GPS device rework them and make them suitable for another application (QGIS). To this end I've tried to perform (What I thought at first would be a simple one) a python based module. According to wire shark analysis.

Source        Destination     Protocol     length   info
192.168.0.1   225.2.5.1       UPD             136   source port : 1045  destination port:6495

I've tried this code found on various sources, like this one.

import socket
import os
UDP_IP = "225.2.5.1"
UDP_PORT = 6495
sock = socket.socket(socket.AF_INET, # Internet
                  socket.SOCK_DGRAM) # UDP
 sock.bind((UDP_IP, UDP_PORT))
while True:
 data, addr = sock.recvfrom(4096) # buffer size is 1024 bytes
 print "received message:", data
os.system("pause")

The problem
This code doesn't work for me.The console windows whether collapse (despite the os.system("pause") or run indefinitely. As I'm not very skilled in python programming nor networking I've tested the provided code with the other IP address and port. As no result came from it I've also started to mix both of them. And finally, gave up and decided to share my issue with the community.
The aim :
I need to be able to access the data contains in this UDP frame with python 2.7 save them in a variable (data) for the next step of my programming project.
Thanks for reading and for your help

Upvotes: 0

Views: 11806

Answers (1)

Daniel
Daniel

Reputation: 42758

You should start your python program from the windows cmd-console or powershell, not from the explorer, then the window stays open and you see error messages. Remove the indentation error and the last line. Be sure, that your computer has the given IP-address. Bind your socket to any address:

import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 6495
sock = socket.socket(socket.AF_INET, # Internet
                  socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
    data, addr = sock.recvfrom(4096)
    print "received message:", data

Upvotes: 3

Related Questions