What exactly is difference between sin_addr.s_addr
and inet_addr
?
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
is what i am using in my programming - what does this achieve?
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 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") Follow this answer to receive notifications.
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).
inet_addr converts an IPv4 address from a string in dotted decimal representation to an integer. This function is deprecated because it does not support IPv6, use inet_pton instead.
So basically, the line about which you are asking loads into the socket the IP address 127.0.0.1, meaning the local host.
addr.sin_addr.s_addr
s_addr is variable that holds the information about the address we agree to accept. So, in this case i put INADDR_ANY because i would like to accept connections from any internet address. This case is used about server example. In a client example i could NOT accept connections from ANY ADDRESS.
ServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
The inet_addr() and inet_network() functions return numbers suitable for use as Internet addresses and Internet network numbers, respectively.
They are different things, as you can see if you put INADDR_ANY in .s_addr your connection will accept all incoming addresses, in your case you're specifying to accept localhost.
This works both for client and for server, server will use INADDR_ANY (if want to accept all incoming connections) and client should just specify one concrete address
fonts: https://wiki.netbsd.org/examples/socket_programming/#index1h3
and man inet_addr
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