I am trying to learn how to better work with binary files using perl instead of ansi C. It seems like a much better language, given the unpack function. I have choosen to use an IP packet for this exercise and am trying to break the IP header into its various pieces, so far, with little luck.

Just trying to read the first 32 bits, IP Version (4 bits), Header Length (4 bits), Type of service field (8 bits), and the total length field (16 bits). The following is the code that I am using to read these 32 bits, obviously I have not grasped something from the pack/unpack documents.
#!/usr/bin/perl -w use strict; my $fname = "ip.header"; open(FILE,$fname) or die $!; binmode(FILE); #read the first 32 bits read(FILE, my $foo, 4); my $ver = unpack "b4", $foo; my $hlen = unpack "b4", $foo; my $tos = unpack "b8", $foo; my $len = unpack "n", $foo; print "Ver = $ver, hlen = $hlen, tos = $tos, len = $len\n"; close FILE;
The results from this is as follows:
Ver = 1111, hlen = 1111, tos = 11111100, len = 16194

Any enlightenment would be wonderful. As this is an attempt to learn pack/unpack better, please do not point to modules that will parse IP headers for me, i thnk that would be rather self defeating in the long run.

In reply to IP Header by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.