I am following the example given in An Introductory 4.4BSD Interprocess Communication Tutorial where it is the process of showing how to communicate using datagrams in the internet domain. In examples, 6a and 6b , 6a sets the port and the hostname
name.sin_addr.s_addr = INADDR_ANY;
name.sin_port = 0;
From what I understand, INADDR_ANY is a wildcard value allowing the socket to receive from anywhere. But, I cannot send from anywhere and explicitly set the hostname in 6b
hp = gethostbyname(argv[1]);
So what hostname would be valid here? When I have tried
program6b localhost 0
But that says it cannot assign the requested address (I have used other addresses and the same message). 6a says that “Socket has port #0” though this means it listens on all ports right? In any case I tried setting the post manually so that “Socket has port #53790”. Netstat shows it is listening
udp4 0 0 *.53790 .
And using the command
program6b localhost 53790
I get a response that the data has been received from the socket which reads. So, I partially understand what is going on, but I would like to know how the example should work for port#0.
Port 0, both UDP and TCP cannot be normally used. They are indicated in the sockets API
bindto request that the Operating System assign an arbitrary free port to the application. It is usually done with client code, that doesn’t care about the specific port used. Server code, in the other hand, usually specifies a known port.About the
INADDR_ANY, when doing the localbind, it means:If instead you indicate an address, it should be an address of your machine, and refers to the network interface that owns that address. Then:
As a note: you cannot listen to every port at the same time, unless you use some kind of raw socket. But not with UDP or TCP.