简体   繁体   中英

timeval to uint64_t network bits

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM