Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "sin_addr.s_addr " and "inet_addr"?

Tags:

sockets

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?

like image 529
user3554806 Avatar asked Apr 20 '14 20:04

user3554806


People also ask

What does Inaddr_any mean?

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 .

What is value of 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.


2 Answers

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.

like image 87
Zoyd Avatar answered Nov 03 '22 07:11

Zoyd


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

like image 38
VMS Avatar answered Nov 03 '22 07:11

VMS