gpt4 book ai didi

c - timeval 到 uint64_t 网络位

转载 作者:行者123 更新时间:2023-11-30 16:15:45 29 4
gpt4 key购买 nike

我希望将 timeval 字段附加到我的自定义数据包 header 中。面临类型转换的问题。

标题中我的自定义字段

struct pkthdr {
uint64_t sec;
uint64_t usec;
}

Linux timeval 结构体

struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
}

初始化

struct pkthdr *hdr;
struct timeval *tm;
gettimeofday(&tm, 0);
hdr->sec = htonl(tm->tv_sec);
hdr->usec = htonl(tm->tv_usec);

以下行导致段错误

hdr->sec = htonl(tm->tv_sec);
hdr->usec = htonl(tm->tv_usec);

最佳答案

您已经创建了指向 struct timevalstruct pkthdr 的指针,但实际上尚未分配任何要指向的内存,因此当您尝试执行以下操作时,您正在调用未定义的行为为 hdr->sechdr->usec

赋值

您还向 gettimeofday 传递了错误的类型,因为您传递的是 struct timeval ** 而不是 struct timeval

尝试创建实际的结构而不是指向它们的指针:

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

检查以确保 hdr.sechdr.usec 中的数据确实是您想要的,因为这可能不正确。我对使用 htonl 有一些保留,因为它处理 32 位数据,而您的预期结果是 64 位。

关于c - timeval 到 uint64_t 网络位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56992597/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com