Programming with pcap (2002)
tcpdump.org
tcpdump.org
[1] http://jvns.ca/blog/2014/08/12/what-happens-if-you-write-a-t...
[2] http://stackoverflow.com/questions/6878603/strange-raw-socke...
[0] https://github.com/thasenpusch/bpf-example/blob/master/main....
The only non GPL solutions I've found are libntoh[1] and libtins[2]. Both are nice, but libtins is much more powerful out of the box, taking care of the pcap code as well. There's one or two things I don't like with the API of libtins, but overall it's a pretty nice library if you want to capture / inject packets.
[1] https://github.com/sch3m4/libntoh [2] http://libtins.github.io/
For each TCP flow (each side of an open connection), open a file. Remember the initial sequence number (ISN) for the flow. Now, when a new segment comes in, use its seqno delta the ISN to seek to the correct offset in the file; write the segment contents to that location.
This is, like, 10 lines of code.
Naturally, in a production application, you won't really use FILE-stars or fds to track connections. But it's very straightforward to build an array-based ADT that provides the open/close/read/write/seek semantics of a file --- much simpler than TCP. Meanwhile, you get to start with working code to test against.
Writing a simple protocol dissector, starting with IP, then TCP, then app-level protocols is a good project. I had to do something similar many moons ago. You'll get a sense of what's actually being put on the wire, and what your networking stack is doing for you behind the scenes.