[Haskell-cafe] Interpreting fields in a buffer

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Mon Jan 26 10:34:06 EST 2004

> I have a question related to a program I'm writing. I have to
> handle IP packets, which will be read into a buffer. What is the
> best haskell idiom for getting access to the fields in the buffer?

There's no way in Haskell to define a datastructure with a particular memory 
layout.  (Strictly, there's no way to do it in ANSI C either but it's easy 
enough to work with what C gives you.)

To access the fields, you will need to write a bunch of functions to read them 
out (and write them if you need).  There's basically two approaches:

1) Write access functions in C and use the ffi interface to call them.
   For example, you might have a function to read the TTL field given
   a pointer to the IP header.

2) Write access functions in Haskell using functions from the Storable
   class and associated libraries.


   To do this, you need to know the offset (in bytes) of each field 
   of the data structure. hsc2hs is great for doing this kind of thing.

> Is there a way in haskell to declare the format of the header, then
> access the components of the buffer as elements of those types?
> I'm only going to do read access on the buffer (an unboxed array).

I would lean towards leaving the buffer over in C land instead of loading it 
into a Haskell buffer.  (Of course, it depends a bit on how much processing 
of the packet you will be doing in Haskell.)

Hope this helps,

Alastair Reid     www.haskell-consulting.com

More information about the Haskell-Cafe mailing list