sin_addr.s_addr = INADDR_ANY;需要 htonl 吗? [英] Does sin_addr.s_addr = INADDR_ANY; need htonl at all?

查看:113
本文介绍了sin_addr.s_addr = INADDR_ANY;需要 htonl 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了两个线程:

带有 recv-timeout 的套接字:出了什么问题用这个代码?

使用c 中的 FILE 流

一个使用 htonl 而另一个没有.

one uses htonl and the other doesn't.

哪个是对的?

推荐答案

由于其他常量如 INADDR_LOOPBACK 是主机字节顺序,我认为这个系列中的所有常量都应该有 htonl 应用于它们,包括 INADDR_ANY.

Since other constants like INADDR_LOOPBACK are in host byte order, I submit that all the constants in this family should have htonl applied to them, including INADDR_ANY.

(注意:我在@Mat 编辑时写了这个答案;他的答案现在还说最好保持一致并始终使用 htonl.)

(Note: I wrote this answer while @Mat was editing; his answer now also says it's better to be consistent and always use htonl.)

基本原理

如果你这样写,对你的代码的未来维护者来说是一种危险:

It is a hazard to future maintainers of your code if you write it like this:

if (some_condition)
    sa.s_addr = htonl(INADDR_LOOPBACK);
else
    sa.s_addr = INADDR_ANY;

如果我正在查看这段代码,我会立即质疑为什么其中一个常量应用了 htonl 而另一个没有.我会将其报告为错误,无论我是否碰巧拥有 INADDR_ANY 始终为 0 的内部知识",因此转换它是无操作的.

If I were reviewing this code, I would immediately question why one of the constants has htonl applied and the other does not. And I would report it as a bug, whether or not I happened to have the "inside knowledge" that INADDR_ANY is always 0 so converting it is a no-op.

您编写的代码不仅要具有正确的运行时行为,还应该在可能的情况下显而易见并且易于相信它是正确的.出于这个原因,您不应该去掉 INADDR_ANY 周围的 htonl.我看到的不使用 htonl 的三个原因是:

The code you write is not only about having the correct runtime behavior, it should also be obvious where possible and easy to believe it is correct. For this reason you should not strip out the htonl around INADDR_ANY. The three reasons for not using htonl that I can see are:

  1. 使用 htonl 可能会冒犯有经验的套接字程序员,因为他们知道它什么也不做(因为他们知道常量的值).
  2. 省略它需要更少的输入.
  3. 虚假的性能"优化(显然无关紧要).
  1. It may offend experienced socket programmers to use htonl because they will know it does nothing (since they know the value of the constant by heart).
  2. It requires less typing to omit it.
  3. A bogus "performance" optimization (clearly it won't matter).

这篇关于sin_addr.s_addr = INADDR_ANY;需要 htonl 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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