in reply to Need help with (un)pack templates

CCnnnCCa2CCCCCCCCa*

IP v4 Header format
C 4-bit version, 4-bit header length
C 8-bit type of service
n 16-bit total length (in bytes)
n 16-bit identification
n 3-bit flags, 13-bit fragment offset
C 8-bit time to live
C 8-bit protocol
a2 16-bit header checksum
CCCC 32-bit source IP address
CCCC 32-bit destination IP address
a* data if any (assuming no IP header options)

Wonder why they used a2 instead of n for the checksum?

Replies are listed 'Best First'.
Re^2: Need help with (un)pack templates
by AnomalousMonk (Archbishop) on Dec 20, 2009 at 15:52 UTC
    CCnnnCCa2CCCCCCCCa*

    Another way to look at this is to realize that whitespace is ignored in a pack/unpack template and that template specifiers can be quantified. The original unpack template might have been written as
        'C C n n n C C a2 C4 C4 a*'
    to slightly clarify just what is going where and that in, e.g.,
        ..., @ip_src[0..3], ... = unpack( ... C4 ... );
    the array slice receives four unsigned bytes.

Re^2: Need help with (un)pack templates
by Subop (Acolyte) on Dec 20, 2009 at 14:01 UTC

    Hey gmargo, that's exactly what I was looking for. Is there a site you got that from? I'd also like to be able to figure out how to decode other protocols as well.

      I typed it in from the front inside cover of my Stevens book (TCP/IP Illustrated Volume 1).

      Wikipedia has it too: http://en.wikipedia.org/wiki/IPv4, but the real gospel is RFC791: http://www.ietf.org/rfc/rfc791.txt.

      Update: Other protocol standards you might like:
      RFC 768 User Datagram Protocol
      RFC 792 Internet Control Message Protocol
      RFC 793 Transmission Control Protocol

        I have that same book and just see the IP header format. How do you know what letters to use in the (un)pack template just by looking at the header format?