简体   繁体   English

uint64_t网络位的时间间隔

[英]timeval to uint64_t network bits

I am looking to append timeval fields into my custom packet header. 我希望将timeval字段附加到我的自定义数据包标题中。 Facing issues with type conversion. 面对类型转换问题。

My custom fields in the header 标头中的我的自定义字段

struct pkthdr {
    uint64_t sec;
    uint64_t usec;
}

Linux timeval struct Linux timeval结构

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 您已经创建了指向struct timevalstruct pkthdr指针,但实际上并未分配任何指向的内存,因此当您尝试为hdr->sechdr->usec分配值时,您正在调用未定义的行为。

You are also passing in the wrong type to gettimeofday as you are passing in a struct timeval ** rather than a struct timeval . 您还传递了错误的类型给gettimeofday因为您传递的是struct timeval **而不是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. 检查并确保hdr.sechdr.usec中的数据确实是您想要的,因为这可能是不正确的。 I have some reservations about use of htonl since that deals with 32-bit data while your intended result is 64 bits. 我对使用htonl有所保留,因为它处理32位数据,而您的预期结果是64位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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