Am 10.07.2011 22:59 schrieb Littlefield, Tyler:
Hello all: I'm working on a server that will need to parse packets sent from a client, and construct it's own packets.
Are these packets sent as separate UDP packets or embedded in a TCP stream? In the first case, you already have packets and only have to parse them. In a stream, you first have to split them up.
In the following, I will talk about UDP datagrams. For TCP, further work is needed.
The setup is something like this: the first two bytes is the type of the packet.
Then you have type = struct.unpack(">H", packet), payload1 = packet[2:]
So, lets say we have a packet set to connect. There are two types of connect packet: a auth packet and a connect packet. The connect packet then has two bytes with the type, another byte that notes that it is a connect packet, and 4 bytes that contains the version of the client.
if type == CONNECT: subtype = struct.unpack("B", payload1) payload2 = payload1[1:] if subtype == CONNECT: upx = payload2.split("\0") assert len(upx) == 3 and upx[-1] == '' username, password = upx[:2] else: assert len(payload2) == 4 version = struct.unpack(">L", payload2)
The auth packet has the two bytes that tells what packet it is, one byte denoting that it is an auth packet, then the username, a NULL character, and a password and a NULL character.
With all of this said, I'm kind of curious how I would 1) parse out something like this (I am using twisted, so it'll just be passed to my Receive function),
I. e., you already have your packets distinct? That's fine. > and how I get the length of the packet with multiple NULL values. With len(), how else? > I'm also looking to build a packet and send it back out, is
there something that will allow me to designate two bytes, set individual bits, then put it altogether in a packet to be sent out?
The same: with struct.pack(). Thomas -- http://mail.python.org/mailman/listinfo/python-list