I am developing a program in which i need to know the values of IP header fields inside my program.Since the IP header is of 20 bytes:
struct ipheader {
unsigned char ip_hl:4, ip_v:4; /* this means that each member is 4 bits */
unsigned char ip_tos;
unsigned short int ip_len;
unsigned short int ip_id;
unsigned short int ip_off;
unsigned char ip_ttl;
unsigned char ip_p;
unsigned short int ip_sum;
unsigned int ip_src;
unsigned int ip_dst;
};
Is there any way that i can know the values of these fields inside my C program?
You should use
setsockopt/getsockopt
routines to interface with socket mechanism. These functions are operate on different levels (IPPROTO_IP
,IPPROTO_TCP
, etc) and some options are available only for particular socket types (e.g. optionIP_TTL
is available only forAF_INET
sockets).get TTL value:
set TTL value:
Some of those values can be set/retrieved via
setsockopt()/getsockopt()
calls at theSOL_IP/IPPROTO/IP
level. Consult your OS' documentation (e.g: on Linuxman 7 ip
).Provided your compiler doesn't introduce any alignment blocks within that structure (make sure that
CHAR_BIT
is 8 andsizeof(struct ipheader)
is 20), you should just be able to include it in your code as-is, and then add something like:In that code, you will have an IP header pointed to by
blk
, which is probably achar*
. Casting it to the correct pointer type will allow you to easily access the fields.The following complete program shows this in action:
Output is, as expected: