Question about INADDR_ANY - linux

The constant INADDR_ANY is the so-called IPv4 wildcard address. The
wildcard IP address is useful for applications that bind Internet
domain sockets on multihomed hosts. If an application on a multihomed
host binds a socket to just one of its host’s IP addresses, then that
socket can receive only UDP datagrams or TCP connection requests sent
to that IP address. However, we normally want an application on a
multihomed host to be able to receive datagrams or connection requests
that specify any of the host’s IP addresses, and binding the socket to
the wildcard IP address makes this possible.
struct sockaddr_in server_address;
int server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&server_address, 0, sizeof(struct sockaddr_in));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY); // here is my quesion
server_address.sin_port = htons(9734);
bind(server_sockfd, (struct sockaddr*)&server_address, sizeof(server_address));
Question>
If we bind the socket to a specific IP address, then the socket can only receive UPD/TCP requests sent sent to that IP address.
As I show in the above code, now the socket server_sockfd is bound with INADDR_ANY.
I just feel confused here b/c if the socket can receive any request on the internet, how it can still work well. There are tons of requests of UDP/TCP on internet, if the socket responses to everybody,
, how can it still work?
// updated code for client side //
int
main(int argc, char *argv[])
{
struct sockaddr_in6 svaddr;
int sfd, j;
size_t msgLen;
ssize_t numBytes;
char resp[BUF_SIZE];
if (argc < 3 || strcmp(argv[1], "--help") == 0)
usageErr("%s host-address msg...\n", argv[0]);
/* Create a datagram socket; send to an address in the IPv6 somain */
sfd = socket(AF_INET6, SOCK_DGRAM, 0); /* Create client socket */
if (sfd == -1)
errExit("socket");
memset(&svaddr, 0, sizeof(struct sockaddr_in6));
svaddr.sin6_family = AF_INET6;
svaddr.sin6_port = htons(PORT_NUM);
if (inet_pton(AF_INET6, argv[1], &svaddr.sin6_addr) <= 0)
fatal("inet_pton failed for address '%s'", argv[1]);
/* Send messages to server; echo responses on stdout */
for (j = 2; j < argc; j++) {
msgLen = strlen(argv[j]);
if (sendto(sfd, argv[j], msgLen, 0, (struct sockaddr *) &svaddr,
sizeof(struct sockaddr_in6)) != msgLen)
fatal("sendto");
numBytes = recvfrom(sfd, resp, BUF_SIZE, 0, NULL, NULL);
if (numBytes == -1)
errExit("recvfrom");
printf("Response %d: %.*s\n", j - 1, (int) numBytes, resp);
}
exit(EXIT_SUCCESS);
}
// updated for server side code
int
main(int argc, char *argv[])
{
struct sockaddr_in6 svaddr, claddr;
int sfd, j;
ssize_t numBytes;
socklen_t len;
char buf[BUF_SIZE];
char claddrStr[INET6_ADDRSTRLEN];
/* Create a datagram socket bound to an address in the IPv6 somain */
sfd = socket(AF_INET6, SOCK_DGRAM, 0);
if (sfd == -1)
errExit("socket");
memset(&svaddr, 0, sizeof(struct sockaddr_in6));
svaddr.sin6_family = AF_INET6;
svaddr.sin6_addr = in6addr_any; /* Wildcard address */
svaddr.sin6_port = htons(PORT_NUM);
if (bind(sfd, (struct sockaddr *) &svaddr,
sizeof(struct sockaddr_in6)) == -1)
errExit("bind");
/* Receive messages, convert to uppercase, and return to client */
for (;;) {
len = sizeof(struct sockaddr_in6);
numBytes = recvfrom(sfd, buf, BUF_SIZE, 0,
(struct sockaddr *) &claddr, &len);
if (numBytes == -1)
errExit("recvfrom");
/* Display address of client that sent the message */
if (inet_ntop(AF_INET6, &claddr.sin6_addr, claddrStr,
INET6_ADDRSTRLEN) == NULL)
printf("Couldn't convert client address to string\n");
else
printf("Server received %ld bytes from (%s, %u)\n",
(long) numBytes, claddrStr, ntohs(claddr.sin6_port));
for (j = 0; j < numBytes; j++)
buf[j] = toupper((unsigned char) buf[j]);
if (sendto(sfd, buf, numBytes, 0, (struct sockaddr *) &claddr, len) !=
numBytes)
fatal("sendto");
}
}
// updated for how to run this server/client programs.
$ ./server_program &
[1] 31047
$ ./client_program ::1 ciao // Send to server on local host
Server received 4 bytes from (::1, 32770)
Response 1: CIAO

It doesn't get requests for every IP address on the internet(a), it gets requests for every IP address that it services. For example, it may have multiple NICs, each with a separate IP address or it may have a single NIC capable of managing multiple IP addresses (it may even have multiple NICs, each capable of handling multiple IP addresses.
The key snippet to look at is:
... we normally want an application on a multi-homed host to be able to receive datagrams or connection requests that specify any of the host’s IP addresses (my italics).
In other words, you may have a multi-homed set-up where your machine services 10.0.0.15 and 10.0.0.16. Using INADDR_ANY will allow you to pick up traffic for both those addresses, without picking up requests for 10.0.0.17 which may be the machine on the other end of the bench (or other side of the planet).
The following table, with the top row being request destinations and the left column being the address you're listening on, shows whether you'll be given a request (Y) or not (N):
Request to> 10.0.0.15 10.0.0.16 10.0.0.17
Bind to: *-------------------------------
10.0.0.15 | Y N N
10.0.0.16 | N Y N
INADDR_ANY | Y Y N
(a) It doesn't even see the vast majority of requests on the net. The vast majority don't even make it to your nearest router (or probably even your ISP). Even those that do make it to your nearest router, your particular machine might not see if they're destined for another machine on the local segment (promiscuous mode notwithstanding).

Related

multicast: Linux *must not* bind socket to a specific # but Windows *must*

I have a mdns service discovery that uses the following code for initialization
void mdnssd_init(struct in_addr host, bool compliant) {
int sock;
int res;
struct ip_mreq mreq;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
char param = 32;
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (void*) &param, sizeof(param));
int enable = 1
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &enable, sizeof(enable));
param = 1;
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, (void*) &param, sizeof(param));
#ifndef _WIN32
if (compliant) {
enable = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*)&enable, sizeof(enable));
}
#endif
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
/*
* Sending *from * 5353 indicates that we do compliant mDNS query. If we chose
* random ports, the ttl will be much shorter.
*/
if (compliant) addr.sin_port = htons(MDNS_PORT);
// Windows must bind this socket to a specific address, others must not (it's *must*)
#ifdef _WIN32
addr.sin_addr.s_addr = host.s_addr;
#else
addr.sin_addr.s_addr = INADDR_ANY;
#endif
socklen_t addrlen = sizeof(addr);
res = bind(sock, (struct sockaddr *) &addr, addrlen);
if (res < 0) return;
// set outgoing interface for multicast (it's optional, INADDR_ANY could be used)
setsockopt (sock, IPPROTO_IP, IP_MULTICAST_IF, (void*) &host.s_addr, sizeof(host.s_addr));
// set multicast groups we are interested by to receive such packets
memset(&mreq, 0, sizeof(mreq));
mreq.imr_multiaddr.s_addr = inet_addr(MDNS_MULTICAST_ADDRESS);
mreq.imr_interface.s_addr = host.s_addr; // optional, INADDR_ANY can be used
setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*) &mreq, sizeof(mreq));
}
It works on all platforms (Linux, Windows, Solaris, FreeBSD, MacOS) but I really don't understand why I need that binding difference between Linux and Windows.
On Linux, if I bind the socket to the address I want to use to send/receive, multicast traffic is not received. Note that queries that require unicast response are properly answered. I understand that some settings here are optional and INADDR_ANY can be used, letting the OS select what interface to send request and receive response (and it works).
On the contrary, on Windows, if the socket is not bound to a specific address, but set to INADDR_ANY, then no multicast traffic is received. Same, queries requiring unicast responses are received.
So it's very puzzling to me that not both options work. I should be able to bind the socket to the address that will be used for sending/receiving - or not. It should work either way, no?

How can I send more bytes using Bluez L2CAP?

I have the following code that connects to another machine using BlueZ and sends packets:
struct sockaddr_l2 addr = { 0 };
int s, status;
char dest[18] = "DC:FB:48:6B:BF:0B";
int socket1;
int32_t value = 0;
// allocate a socket
socket1 = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
// set the connection parameters (who to connect to)
addr.l2_family = AF_BLUETOOTH;
addr.l2_psm = htobs(0x1001);
str2ba( dest, &addr.l2_bdaddr );
status = connect(socket1, (struct sockaddr *)&addr, sizeof(addr));
while( status != 0)
{
status = connect(socket1, (struct sockaddr *)&addr, sizeof(addr));
std::cout << "Waiting for DC:FB:48:6B:BF:0B" << std::endl;
sleep(2);
}
while (true)
{
double data[512] = {0.0};
memset(data, 0, 512);
status = write(socket1, data, 512);
}
As you can see, I just send 512 bytes and other machine reads them just fine. However, when I try to increase to 1000 bytes, other machine can no longer accept any bytes and just does nothing.
How can I send more bytes in this case? I am using Linux CentOS 8.
By default the maximum transmission rate of L2CAP is 672 bytes. I would recommend you to try setting the maximum transmission unit to your required value.
Have a look at "4.3.1 Maximum Transmission Unit" here.

linux multicast join doesn't, why?

I need to receive multicast data from two sources on one ethernet connection, 224.0.31.132 port 14384 and 224.0.31.130 port 14382.
First I tried to bind with port 14384 and then join both ip addresses, but I only get the data from 224.0.31.132.
If I bind with 14382 and join both, I only get the data from 224.0.31.130.
So then I tried to create two sockets, bind the first to 14384 and join 224.0.31.132, then bind the second to 14382 and join 224.0.31.130.
When I do that, I get the data from 224.0.31.130, but not from 224.0.31.132, and ip maddr show shows that the join to 224.0.31.132 has apparently been deleted by the setting up of the second socket.
What do I do to receive data from these two sources on the single eth port?
Here is code for first approach:
/* Create a datagram socket on which to receive. */
int sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd < 0)
{
perror("Opening datagram socket error");
exit(1);
}
else
cout<<"Opening datagram socket....OK."<<endl;
/* Enable SO_REUSEADDR to allow other */
/* applications to receive copies of the multicast datagrams. */
{
int reuse = 1;
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0)
{
perror("Setting SO_REUSEADDR error");
close(sd);
exit(1);
}
else
cout<<"Setting SO_REUSEADDR...OK."<<endl;
}
/* Enable SO_REUSEPORT to allow multiple uses of receive port */
{
int reuse = 1;
if(setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, (char *)&reuse, sizeof(reuse)) < 0)
{
perror("Setting SO_REUSEPORT error");
close(sd);
exit(1);
}
else
cout<<"Setting SO_REUSEPORT...OK."<<endl;
}
/* Bind to the proper port number with the IP address */
/* specified as INADDR_ANY. */
struct sockaddr_in localSock;
memset((char *) &localSock, 0, sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(14384);
localSock.sin_addr.s_addr = INADDR_ANY;
if(bind(sd, (struct sockaddr*)&localSock, sizeof(localSock)))
{
perror("Binding datagram socket error");
close(sd);
exit(1);
}
else
cout<<"Binding datagram socket...OK."<<endl;
/* Join the multicast groups on the local nic interface. */
struct ip_mreq group;
group.imr_interface.s_addr = inet_addr("0.0.0.0");
int ipcount = stoi(getSetup("mcstcount"));
while(ipcount>0)
{
string which = "listenip" + to_string(ipcount);
cout<<"listen to "<<getSetup(which.c_str())<<endl;
group.imr_multiaddr.s_addr = inet_addr(getSetup(which.c_str()).c_str());
ipcount--;
if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
{
perror("Adding multicast group error");
close(sd);
exit(1);
}
else
cout<<"Adding multicast group...OK."<<endl;
}
// process Mdp feed
while( !stop_cond )
{
/* Read from the socket. */
const int DBUFSZ = 5000;
uint8_t databuf[DBUFSZ];
int datalen;
datalen=read(sd, databuf, DBUFSZ);
if(datalen < 0)
{
perror("Reading datagram message error");
close(sd);
exit(1);
}
//process data
}
Here is resulting output:
Opening datagram socket....OK.
Setting SO_REUSEADDR...OK.
Setting SO_REUSEPORT...OK.
Binding datagram socket...OK.
listen to 224.0.33.80
Adding multicast group...OK.
listen to 224.0.31.130
Adding multicast group...OK.
listen to 224.0.31.132
Adding multicast group...OK.
But data only comes in from 224.0.31.132.
Concluded one cannot use a single socket as there are multiple ports to receive from. Went back to approach two, using multiple sockets. Got it working, not sure what was wrong the first time.

Select MAC address for binding to a specific bluetooth adapter

The following piece of code binds a Bluetooth socket. My expectation is that the call to bind() (or to listen()) with that MAC address as argument fails, because when using AF_INET sockets, I cannot bind() to an IP address that I don't have. This answer suggests that it's possible to select your adapter, but I cannot reproduce that in my experiments.
/* From https://people.csail.mit.edu/albert/bluez-intro/x502.html */
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
// loc_addr.rc_bdaddr = *BDADDR_ANY;
bdaddr_t my_bdaddr = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
loc_addr.rc_bdaddr = my_bdaddr;
loc_addr.rc_channel = (uint8_t) 1;
{
int res = bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
char baddr[128];
ba2str(&loc_addr.rc_bdaddr, baddr);
fprintf(stderr, "bound to %s: %d\n", baddr, res);
}
// put socket into listening mode
{
int res = listen(s, 1);
fprintf(stderr, "Listening: %d\n", res);
}
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
// close connection
close(client);
close(s);
return 0;
}
So I guess my question is: Is my expectation of the bind() having to fail wrong?
The main reason I am concerned with the MAC address is that I want another party to connect to me and send it some data. For the other party to establish a connection, it needs my MAC address and port. Now I can find my MAC address via the DBus API (or probably via some other means) but then I'm afraid that it's racy, e.g. I cannot be sure that the MAC address I queried is the same that I've bound to, because in the time between the query and the bind the user may have removed their Bluetooth adapter and inserted a new one. And before I jump through the hoops of subscribing to BlueZ DBus signals I thought I'd use the MAC for binding the socket.

why my TCP server code send a SYN/ACK on only first packet or only on the first connection?

SOCKET sock;
SOCKET fd;
uint16 port = 18001;
void CreateSocket()
{
struct sockaddr_in server, client; // creating a socket address structure: structure contains ip address and port number
WORD wVersionRequested;
WSADATA wsaData;
int len;
printf("Initializing Winsock\n");
wVersionRequested = MAKEWORD (2, 2);
iResult = WSAStartup (wVersionRequested, &wsaData);
if (iResult != NO_ERROR)
printf("Error at WSAStartup()\n");
// create socket
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
// create socket address of the server
memset( &server, 0, sizeof(server));
// IPv4 - connection
server.sin_family = AF_INET;
// accept connections from any ip adress
server.sin_addr.s_addr = htonl(INADDR_ANY);
// set port
server.sin_port = htons(18001);
//Binding between the socket and ip address
if(bind (sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
//Listen to incoming connections
if(listen(sock,3) == -1){
printf("Listen failed with error code: %d", WSAGetLastError());
}
printf("Server has been successfully set up - Waiting for incoming connections");
for(;;){
len = sizeof(client);
fd = accept(sock, (struct sockaddr*) &client, &len);
if (fd < 0){
printf("Accept failed");
close(sock);
}
//echo(fd);
printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//closesocket(fd);
}
}
The server code is accepting a connection from the client via the ip address and the port number. It is sending SYN/ACK to the client only during the first connection and It is sending like below for the second time: RST / ACK (it is resetting during the second time).
Could anyone tell me what is the error in the above code ??
Look at Accept multiple subsequent connections to socket
Here is a quote: "To service multiple clients, you need to avoid blocking I/O -- i.e., you can't just read from the socket and block until data comes in."

Resources