Reputation: 5747
I am looking for a pythonic way to represent a UDP package consisting of different fields with different length and so.
I saw bitstring, but the process of defining all the fields and their length is quite cumbersome. I probably need to create a class and create a variable for each field and length and also check that they don't get overwritten by larger numbers and so on.
To me that sounds like a job for a library but I could not find one.
Does anyone know of such a library suitable for this task?
Upvotes: 0
Views: 485
Reputation: 1290
The first way is to use a "batteries included"-module like:
Now if you want to create a custom packet, two ways to do it are either
using scapy
to create a new custom protocol, or you can use ctypes
and struct
like so:
import os
import struct
from ctypes import *
class myUDP(Structure):
_fields_ = [
("sport", c_ushort),
("dport", c_ushort),
("sum", c_ushort),
("len", c_ushort)
]
def __new__(self, packet=None):
return self.from_buffer_copy(packet)
def __init__(self, packet=None):
# unpack your data, etc...
self.srcport = struct.unpack("H",self.sport)
The above is a low-level, simple and as minimal as possible example-representation of the UDP header(untested):
Though that can a bit difficult to be used in real-world scenarios, with complicated protocols, since it demands a lot of technical work, error handling etc... in order to be a complete packet decoder.
Upvotes: 1
Reputation: 1
You can use scapy for packet manipulation
from scapy.all import *
packet = IP(src="1.1.1.1", dst="2.2.2.2")/UDP(dport=4321, sport=123)/"payload"
print str(packet)
# output: 'E\x00\x00#\x00\x01\x00\x00@\x11t\xc4\x01\x01\x01\x01\x02\x02\x02\x02\x00{\x10\xe1\x00\x0f+?payload'
Upvotes: 0