What OS are you working on ? Linux has a built-in "tcpdump" program that can (selectively) capture what you want. There are options in Windows, both Open source (windump) and MS-specific (I believe the MS network monitor is now a part of SMS).
If you want to capture this info in perl, use the Net::Pcap series of modules.
"By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest."