【问题标题】:inet_netof() and returned host-byte orderinet_netof() 并返回主机字节顺序
【发布时间】: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


【解决方案1】:

0x00C0A832,正如你所说,0.192.168.50

它按主机字节顺序和正确的值。

文档中的措辞有点含糊(“返回 Internet 地址的网络号部分”),但如果我检查 implementation,就会出现右移,所以一切似乎都很好。

【讨论】:

    【解决方案2】:
    1. inet_addr() 返回网络字节顺序。
    2. 您收到的网络号是三个字节。
    3. inet_netof() 返回主机字节顺序,即 Little-endian。由于您的机器是 Little-endian,因此 inet_netof() 返回的字节与 inet_addr() 返回的输出相比顺序相反。

    参考请见man 3 inet

    【讨论】:

    • 是的。我解决了我的错误想法。我假设 inet_addr() 返回 little-endian 但正如您所指出的那样是错误的。相反,它是大端。如果我假设 inet_addr() 返回网络字节顺序(它确实如此),那么 inet_netof() 的输出完全有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2013-10-23
    • 2012-06-11
    • 1970-01-01
    • 2015-06-28
    • 2016-11-25
    相关资源
    最近更新 更多