There are several libraries that allow you to do this, and also some open-source tools like Ethereal that allows packet logging. Ethereal is a great and well-tested piece of software that runs on a variety of platforms. Grab some of their code and read through, I'm sure you'll find your answer there