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?
This is an IP address that is used when we don't want to bind a socket to any specific IP. Basically, while implementing communication, we need to bind our socket to an IP address. When we don't know the IP address of our machine, we can use the special IP address INADDR_ANY .
INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind() , the socket accepts connections to all the IPs of the machine.
There are several special addresses: INADDR_LOOPBACK (127.0. 0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0. 0.0) means any address for binding; INADDR_BROADCAST (255.255. 255.255) means any host and has the same effect on bind as INADDR_ANY for historical reasons.
sin_addr is the IP address in the socket (the socket structure also contains other data, such as a port). The type of sin_addr is a union, so it can be accessed in three different ways : as s_un_b (four 1-byte integers), s_un_w (two 2-bytes integers) or as s_addr (one 4-bytes integer).
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:
htonl
because they will know it does nothing (since they know the value of the constant by heart).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With