07-27-2023, 10:57 AM
I recently ran into [this blog post][1] which describes a TCP server client using libev. The sever uses `INADDR_ANY` to bind to an interface which is something I'm familiar with. However, I was surprised to see `INADDR_ANY` in the client code as well. The relevant code on the client code is as follows:
// Create client socket
if( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("socket error");
return -1;
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_NO);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Connect to server socket
if(connect(sd, (struct sockaddr *)&addr, sizeof addr) < 0)
{
perror("Connect error");
return -1;
}
Specifically I'm interesed in the line:
addr.sin_addr.s_addr = htonl(INADDR_ANY);
On the server side I understand that `INADDR_ANY` will bind the port to all available interfaces, but I'm not sure how this makes sense on the client side. In the end, the client will need to connect on a particular interface. Previously I have always specified the IP address or used `INADDR_LOOPBACK`.
[The Linux IP man page][2] doesn't talk about using `INADDR_ANY` on the client side. I did find [another Stack Overflow post here][3] which says that the OP should use `INADDR_ANY` on the client side, but gives no justification or explanation.
So what is this actually doing? Is it trying all interfaces until it finds one where the port is available for connection? What order does this happen in?
Thanks for your answers!
[1]:
// Create client socket
if( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("socket error");
return -1;
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_NO);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Connect to server socket
if(connect(sd, (struct sockaddr *)&addr, sizeof addr) < 0)
{
perror("Connect error");
return -1;
}
Specifically I'm interesed in the line:
addr.sin_addr.s_addr = htonl(INADDR_ANY);
On the server side I understand that `INADDR_ANY` will bind the port to all available interfaces, but I'm not sure how this makes sense on the client side. In the end, the client will need to connect on a particular interface. Previously I have always specified the IP address or used `INADDR_LOOPBACK`.
[The Linux IP man page][2] doesn't talk about using `INADDR_ANY` on the client side. I did find [another Stack Overflow post here][3] which says that the OP should use `INADDR_ANY` on the client side, but gives no justification or explanation.
So what is this actually doing? Is it trying all interfaces until it finds one where the port is available for connection? What order does this happen in?
Thanks for your answers!
[1]:
[To see links please register here]
[2]:[To see links please register here]
[3]:[To see links please register here]