views:

9

answers:

1

Here's an example 'Packet Structure' image: http://freesoft.org/CIE/Course/Section3/7.htm

Lets say I had a small Python program that listened on X port and captured that packet and saved it to the variable 'data'.

How would I pull out the packet information from data? For example, say I wanted to read the 'version', is it just:

print data[0:4] ?

How would I get the Source IP Address?

I've been doing more socket coding lately and have ran into quite a few of these 'packet structure' images. I'm yet to figure out how to apply them to my code :/

A: 

Note that your example shows an IP header - if you are simply using sockets, you will not see this information (its already been digested by the system IP and TCP stacks).

If you want to capture raw data, look into using libpcap, which will allow raw packets. You can also use tcpdump to produce a file with raw packets.

As for structures, you can read the first 4 bytes if your data was a string with your command. You would likely want to encode the string as "hex" (or integers for the normal representation) or you will see "garbage" characters instead.

For more powerful unpacking, use the struct module which comes with python.

Yann Ramin
How would I go about reading the second line of that packet? To, say, get the 'Flags' field? I'll definitely take a look at the struct module. Cheers
Martin
Read it left to right, top to bottom. The second line in this case is simply the second byte (bits 0-31 per line).
Yann Ramin