[英]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 timeval
和struct pkthdr
指针,但实际上并未分配任何指向的内存,因此当您尝试为hdr->sec
和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
. 您还传递了错误的类型给
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.sec
和hdr.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.