I am trying to program some sockets and so, on the server side, I use htonl(INADDR_ANY)
. To the extent I understood, it seems to me that this function generates a random IP (am I correct ?). In fact, I want to bind my socket with my localhost
. But if I run this
printf("%d",htonl(INADDR_ANY));
I get 0 as a return value. Could someone bring some explanation ?
INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
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.
To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by
my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")
or by
my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
Source: Stackoverflow.com