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")
bind()
ofINADDR_ANY
does NOT "generate a random IP". It binds the socket to all available interfaces.For a server, you typically want to bind to all interfaces - not just "localhost".
If you wish to bind your socket to localhost only, the syntax would be
my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
, then callbind(my_socket, (SOCKADDR *) &my_sockaddr, ...)
.As it happens,
INADDR_ANY
is a constant that happens to equal "zero":http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html
If you're not already familiar with it, I urge you to check out Beej's Guide to Sockets Programming:
http://beej.us/guide/bgnet/
Since people are still reading this, an additional note:
Also:
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind toinet_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.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 callingbind()
, 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
or by