I am looking to append timeval fields into my custom packet header. Facing issues with type conversion.
My custom fields in the header
struct pkthdr {
uint64_t sec;
uint64_t usec;
}
Linux timeval struct
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
}
Initialization
struct pkthdr *hdr;
struct timeval *tm;
gettimeofday(&tm, 0);
hdr->sec = htonl(tm->tv_sec);
hdr->usec = htonl(tm->tv_usec);
Following lines cause segmentation error
hdr->sec = htonl(tm->tv_sec);
hdr->usec = htonl(tm->tv_usec);
You have created pointers to
struct timevalandstruct pkthdr, but you have not actually allocated any memory to point to, so you are invoking undefined behavior when you try to assign a value tohdr->secandhdr->usecYou are also passing in the wrong type to
gettimeofdayas you are passing in astruct timeval **rather than astruct timeval.Try, instead, creating the actual structs instead of pointers to them:
Check to make sure the data in
hdr.secandhdr.usecare actually what you want, as that might not be correct. I have some reservations about use ofhtonlsince that deals with 32-bit data while your intended result is 64 bits.