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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since other constants like
INADDR_LOOPBACKare in host byte order, I submit that all the constants in this family should havehtonlapplied to them, includingINADDR_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 I were reviewing this code, I would immediately question why one of the constants has
htonlapplied and the other does not. And I would report it as a bug, whether or not I happened to have the “inside knowledge” thatINADDR_ANYis 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
htonlaroundINADDR_ANY. The three reasons for not usinghtonlthat I can see are:htonlbecause they will know it does nothing (since they know the value of the constant by heart).