c - 通过 POSIX 套接字发送 64 位变量的可移植方式

标签 c sockets 64-bit posix portability

我正在设计自定义网络协议(protocol),我需要发送 uint64_t变量(表示文件的字节长度)到 socketportablePOSIX-compliant方式。

不幸的是manual表示宽度为 64 的整数类型不保证存在:

If an implementation provides integer types with width 64 that meet these requirements, then the following types are required: int64_t uint64_t

此外,没有符合 POSIX 标准的 htonl, htons, ntohl, ntohs 等价物(注意 bswap_64 is not 符合 POSIX)。

通过套接字发送 64 位变量的最佳做法是什么?

最佳答案

当然,您可以只应用 htonl() 两次:

const uint64_t x = ...
const uint32_t upper_be = htonl(x >> 32);
const uint32_t lower_be = htonl((uint32_t) x);

这将为您提供两个 32 位变量,其中包含 64 位变量 x 的高 32 位和低 32 位的大端版本。

如果你是严格的 POSIX,你不能使用 uint64_t 因为它不能保证存在。然后你可以这样做:

typedef struct {
 uint32_t upper;
 uint32_t lower;
} my_uint64;

当然,只有 htonl() 直接。

关于c - 通过 POSIX 套接字发送 64 位变量的可移植方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526279/

相关文章:

c - Mac C 程序在字符串初始值设定项上崩溃

c - 寻找一种工具来告诉我 C 中的计算需要哪些整数宽度才不会溢出

c - 在巨大的位图中搜索第一个设置位

debugging - 如何在 Windows 7 x64 上使用 Visual C++ 6 进行调试?

ios - Swift 4 OutputStream 产生的输出多于输入

java - 如何解析通过 TCP 收到的损坏消息

javascript - "Access is denied"通过在 Windows XP x64 上使用 JScript 执行 .hta 文件

c - 在 C 中像 shell 一样解析命令

c - 来自 printf() 的随机段错误,有人可以帮忙解释一下吗?

algorithm - 测量两台机器之间的链路质量