0

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);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
pgrad13
  • 1
  • 3

1 Answers1

0

You have created pointers to struct timeval and struct 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 to hdr->sec and hdr->usec

You are also passing in the wrong type to gettimeofday as you are passing in a struct timeval ** rather than a struct timeval.

Try, instead, creating the actual structs instead of pointers to them:

struct pkthdr hdr;
struct timeval tm;
gettimeofday(&tm, NULL);
hdr.sec = htonl(tm.tv_sec);
hdr.usec = htonl(tm.tv_usec);

Check to make sure the data in hdr.sec and hdr.usec are actually what you want, as that might not be correct. I have some reservations about use of htonl since that deals with 32-bit data while your intended result is 64 bits.

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29