理解 htonl() 和 ntohl() [英] Understanding htonl() and ntohl()

查看:27
本文介绍了理解 htonl() 和 ntohl()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 unix 套接字来测试向本地主机发送一些 udp 数据包.

I am trying to use unix sockets to test sending some udp packets to localhost.

据我所知,在设置 ip 地址和端口以发送数据包时,我会用转换为网络字节顺序的值填充我的 sockaddr_in.我在 OSX 上,我很惊讶这个

It is my understanding that when setting ip address and port in order to send packets, I would fill my sockaddr_inwith values converted to network-byte order. I am on OSX and I'm astonished that this

printf("ntohl: %d
", ntohl(4711));
printf("htonl: %d
", htonl(4711));
printf("plain: %d
", 4711);

印刷品

ntohl: 1729232896
htonl: 1729232896
plain: 4711

所以这两个函数实际上都没有返回普通值.我本来希望看到结果不同,因为 x86 是小端 (afaik),或者与实际数字 4711 相同.显然我不明白 htonlntohl 和它们的变体都可以.我错过了什么?

So neither function actually returns the plain value. I would have expected to see either the results differ, as x86 is little-endian (afaik), or be identical and the same as the actual number 4711. Clearly I do not understand what htonl and ntohl and their variants do. What am I missing?

相关代码是这样的:

int main(int argc, char *argv[])
{
   if (argc != 4)
   {
      fprintf(stderr, "%s
", HELP);
      exit(-1);
   }

   in_addr_t rec_addr = inet_addr(argv[1]); // first arg is '127.0.0.1'
   in_port_t rec_port = atoi(argv[2]);      // second arg is port number
   printf("Address is %s
Port is %d
", argv[1], rec_port);
   char* inpath = argv[3];

   char* file_buf;
   unsigned long file_size = readFile(inpath, &file_buf); // I am trying to send a file
   if (file_size > 0)
   {
      struct sockaddr_in dest;
      dest.sin_family      = AF_INET;
      dest.sin_addr.s_addr = rec_addr; // here I would use htons
      dest.sin_port        = rec_port;
      printf("ntohs: %d
", ntohl(4711));
      printf("htons: %d
", htonl(4711));
      printf("plain: %d
", 4711);
      int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
      if (socket_fd != -1)
      {
         int error;
         error = sendto(socket_fd, file_buf, file_size + 1, 0, (struct sockaddr*)&dest, sizeof(dest));
         if (error == -1)
            fprintf(stderr, "%s
", strerror(errno));
         else printf("Sent %d bytes.
", error);
      }
   }

   free(file_buf);
   return 0;
}

推荐答案

两个函数都反转字节顺序(在小端机器上).为什么会返回参数本身?

Both functions reverse the bytes' order (on little-endian machines). Why would that return the argument itself?

试试 htons(ntohs(4711))ntohs(htons(4711)).

这篇关于理解 htonl() 和 ntohl()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆