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.