Skip to content

Instantly share code, notes, and snippets.

@nh2
Created November 25, 2012 22:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nh2/4145774 to your computer and use it in GitHub Desktop.
Save nh2/4145774 to your computer and use it in GitHub Desktop.
Haskell PCAP writing / dump (instance Storable PktHdr)
module PktHdrStorableInstance where
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (plusPtr)
import Foreign.Storable
import Network.Pcap
import Network.Pcap.Base (toPktHdr)
#include <pcap.h>
-- From: http://www.haskell.org/haskellwiki/FFI_cook_book
#let alignment t = "%lu", (unsigned long) offsetof(struct { char x__; t (y__); }, y__)
instance Storable PktHdr where
alignment _ = (#alignment struct pcap_pkthdr)
sizeOf _ = (#size struct pcap_pkthdr)
peek = toPktHdr
poke ptr PktHdr { hdrSeconds = s
, hdrUseconds = u
, hdrCaptureLength = cl
, hdrWireLength = wl } = do
let ts = (#ptr struct pcap_pkthdr, ts) ptr
(#poke struct timeval, tv_sec) ts s
(#poke struct timeval, tv_usec) ts u
(#poke struct pcap_pkthdr, caplen) ptr cl
(#poke struct pcap_pkthdr, len) ptr wl
-- | Copies one PCAP file to another by going through all the packets.
--
-- Uses `loop` and `dump`.
copyPcap :: IO ()
copyPcap = do
inHandle <- openOffline "myfile.pcap"
len <- snapshotLen inHandle
link <- datalink inHandle
outHandle <- openDead link len
outDump <- openDump outHandle "myfile-copy.pcap"
_ <- loop inHandle (-1) (procPacket outDump)
return ()
where
procPacket :: DumpHandle -> Callback
procPacket outDump hdr conentPtr = with hdr $ \hdrPtr -> do
dump outDump hdrPtr conentPtr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment