【发布时间】:2015-01-03 00:50:12
【问题描述】:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char **argv) {
unsigned long addr;
unsigned long net_id;
struct sockaddr_in address;
addr = inet_addr("192.168.50.25");
// prints 1932A8C0 in host byte-order which in this case is little-endian
printf("IP-Address in Host-Byte Order: %08X\n", (unsigned int) addr);
// zero the struct out
memset(&address, 0, sizeof address);
// copy address into the struct
memcpy(&address.sin_addr.s_addr, &addr, sizeof addr);
// inet_netof returns the network ID in host byte order
net_id = inet_netof(address.sin_addr);
// prints 00C0A832 Why not 0032A8C0?
printf("Network ID in Host-Byte-Order: %08X\n", (unsigned int) net_id);
return 0;
}
我有一个 little-endian 机器,所以主机字节顺序是 little endian。 IP 地址 192.168.50.25 按主机字节顺序为 0x1932A8C0。这对我来说很明显。
现在,inet_netof 函数以主机字节顺序返回地址 192.168.50.25 的网络 ID。其输出为 0x00C0A832。这让我很困惑。对我来说,这看起来并不像 little-endianness。如果我将其转换为点分十进制,它将是:0.192.168.50。
我会假设网络 ID 在 little-endian 中看起来像这样:0.50.168.192 或 0x0032A8C0 十六进制而不是 inet_netof() 返回 0x00C0A832。
为什么 inet_netof() 返回 0x00C0A832 而不是 0x0032A8C0?
【问题讨论】:
-
网络字节序为大端。
inet_addr()返回网络字节顺序。 -
是的。 inet_addr() 返回网络字节顺序,但我询问的是 inet_netof() 函数。 inet_netof() 函数返回主机字节顺序。
-
啊,我明白了。我在第一个 printf() 语句中犯了一个错误,这显然是网络字节顺序是的。看来我的整个逻辑都出错了?!
标签: c sockets endianness