Parsing UDP Packets
<p>I am building a UDP server to parse and verify incoming UDP packets. I am able to receive and parse packets but the header values are not what I expected.  </p>

<p>This is structure of incoming packet</p>

<p>Packet ID ( 4 bytes )<br>
 Packet Sequence ( 4 bytes )<br>
 XOR Key ( 2 bytes )<br>
 Number of Checksums in packet ( 2 bytes )<br>
 Cyclic checksum CRC32 (variable)</p>

<p>To send the packet, </p>

<pre><code>with open('payloadfile.bin') as op:
    payload = pickle.load(op)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

for i in payload:
    sock.sentto(payload, ('127.0.0.1',4545))
</code></pre>

<p>To receive and parse this packet</p>

<pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind('127.0.0.1',4545)

while 1:
    packet = sock.recvfrom(65565)
    packet = packet[0]

    # parse IP
    ip_header = packet[0:20]
    iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)

    #all the following values are incorrect
    version_ihl = iph[0]
    version = version_ihl &gt;&gt; 4
    ihl = version_ihl &amp; 0xF

    ttl = iph[5]
    protocol = iph[6]
    s_addr = socket.inet_ntoa(iph[8]);
    d_addr = socket.inet_ntoa(iph[9]);

    # parse UDP
    packet = packet[20:28]
    data = packet[header_length:]
    source_port, dest_port, data_length, checksum = struct.unpack("!HHHH", header)
</code></pre>

<p>From what I understand so far, this should be the general structure<br>
IP_HEADER ( UDP_HEADER ( PAYLOAD )))</p>

<p>I want to parse the headers correctly, and then extract payload.<br>
I would really appreciate if some one could point me to the right direction</p>

<p>Unfortunately the standard socket interface doesn't give you access to the data frames that your data arrive in, neither does it include the IP Datagram headers nor the TCP/UDP headers from the transport layer.</p>

<p>To get hold of lower-level data you are forced to use the so-called <em>raw socket interface</em>, which Windows for one tries to block you from using because you might be a hacker. <a href="http://www.binarytides.com/raw-socket-programming-in-python-linux/" rel="nofollow">This article</a> might give you some clues.</p>

python python-2.7 sockets networking udp