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
Was going to add this as a comment, but it got a little long-winded ...
I think it's clear from the answers and the commentary here that htonl()
needs to be used on these constants (albeit that calling it on INADDR_ANY
and INADDR_NONE
are tantamount to no-ops). The problem that I see as to where the confusion arises is that it is not explicitly called out in documentation - someone please correct me if I simply missed it, but I have not seen in the man pages, nor in the include header where it explicitly states that the defines for INADDR_*
are in host order. Again, not a big deal for INADDR_ANY
, INADDR_NONE
, and INADDR_BROADCAST
, but it is significant for INADDR_LOOPBACK
.
Now, I've done quite a bit of low-level socket work in C, but the loopback address rarely, if ever, gets used in my code. Although this topic is over a year old, this very problem just jumped up to bite me in the behind today, and it was because I went on the mistaken assumption that the addresses defined in the include header are in network order. Not sure why I had that idea - probably because the in_addr
structure needs to have the address in network order, inet_aton
and inet_addr
return their values in network order, and so my logical assumption was that these constants would be usable as-is. Throwing together a quick 5-liner to test that theory showed me otherwise. If any of the powers-that-be happen to see this, I would make the suggestion to explicitly call out that the values are, in fact, in host order, not network order, and that htonl()
should be applied to them. For consistency's sake, I would also suggest, as others have done so already here, that htonl()
be used for all of the INADDR_*
values, even if it does nothing to the value.