Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

c - Does sin_addr.s_addr = INADDR_ANY; need htonl at all?

I came across two threads:

Socket with recv-timeout: What is wrong with this code?

Reading / Writing to a socket using a FILE stream in c

one uses htonl and the other doesn't.

Which is right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

Rationale

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;

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.

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. 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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...