If your compiler does not enter any alignment blocks in this structure (make sure CHAR_BIT is 8 and sizeof(struct ipheader) is 20), you should just include it in your code as is, and then add something like:
struct ipheader *iph = (struct ipheader *)blk; printf ("TTL = %d\n", iph->ip_ttl);
In this code, you will have the IP header blk points to, which is probably char* . Casting it to the right type of pointer allows you to easily access fields.
The following complete program shows this in action:
#include <stdio.h> #include <limits.h> struct ipheader { /* 0 */ unsigned char ip_hl:4, ip_v:4; /* 1 */ unsigned char ip_tos; /* 2 */ unsigned short int ip_len; /* 3 */ unsigned short int ip_id; /* 4 */ unsigned short int ip_off; /* 5 */ unsigned char ip_ttl; /* 6 */ unsigned char ip_p; /* 7 */ unsigned short int ip_sum; /* 8 */ unsigned int ip_src; /* 9 */ unsigned int ip_dst; }; int main (void) { char blk[] = { '\x00','\x11','\x22','\x22','\x33','\x33','\x44','\x44', '\x55','\x66','\x77','\x77','\x88','\x88','\x88','\x88', '\x99','\x99','\x99','\x99' }; struct ipheader *iph = (struct ipheader *)(&blk); printf ("TTL = %x\n", iph->ip_ttl); printf ("sum = %x\n", iph->ip_sum); printf ("dst = %x\n", iph->ip_dst); return 0; }
The output, as expected:
TTL = 55 sum = 7777 dst = 99999999
paxdiablo
source share