开发者

Correct command to send in a datagram in the internet domain for port 0

开发者 https://www.devze.com 2023-04-13 01:44 出处:网络
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

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 bind to 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 local bind, it means:

  • Listen at all network interfaces, if the socket is listening.
  • Let the OS choose the appropriate network interface for sending data.

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:

  • If the socket is listening: it will listen only in that network interface.
  • If the socket sends data, it will consider only that network interface.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号