[英]timeval to uint64_t network bits
我希望將timeval字段附加到我的自定義數據包標題中。 面對類型轉換問題。
標頭中的我的自定義字段
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 timeval
和struct pkthdr
指針,但實際上並未分配任何指向的內存,因此當您嘗試為hdr->sec
和hdr->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.sec
和hdr.usec
中的數據確實是您想要的,因為這可能是不正確的。 我對使用htonl
有所保留,因為它處理32位數據,而您的預期結果是64位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.