FFI and endian conversion

  • From: Luke Gorrie <lukego@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 25 Jul 2012 12:32:12 +0200


I'm using LuaJIT's FFI to access things like ethernet frames as if they
were C structures, and I'm wondering what the best way to take care of
endian conversion is. Like: can I easily tell LuaJIT that I want automagic
endian conversion on certain structure fields?

My data structures look like this:

-- PCAP file format:

struct pcap_file {
    /* file header */
    uint32_t magic_number;   /* magic number */
    uint16_t version_major;  /* major version number */
    uint16_t version_minor;  /* minor version number */
    int32_t  thiszone;       /* GMT to local correction */
    uint32_t sigfigs;        /* accuracy of timestamps */
    uint32_t snaplen;        /* max length of captured packets, in octets */
    uint32_t network;        /* data link type */
} __attribute__ ((__packed__));

struct ether_header
  u_int8_t  ether_dhost[ETH_ALEN];      /* destination eth addr */
  u_int8_t  ether_shost[ETH_ALEN];      /* source ether addr    */
  u_int16_t ether_type;                 /* packet type ID field */
} __attribute__ ((__packed__));

and here the first structure can be in either endian (libpcap is flexible)
but the ether_header has to be big-endian, and I'm running on a
little-endian machine.


Other related posts: