简体   繁体   中英

DatagramSocket.Receive without port set

I've recently started to learn about socket usage, more specifically in Java.

In this link is shown a simple client-server UDP application.

My question is: How does the client receives the response with receive() method when this datagramsocket object calling receive doesn't have a port set?

The client initializes its DatagramSocket via the nullary constructor, which binds the socket to some available port (chosen in an unspecified manner) on the wildcard address. That's quite different from not having a port set -- there is a port set, but it is chosen by the computer, not explicitly specified by the program.

When the server receives a message, it extracts not only the message data, but also the source address and port. It sends its response to that address and port. The client successfully receives it via the same socket with which it sent the original message, because it's still bound to the same port, even if you don't know exactly which one that is.

the first time you send a packet using that socket, an ephemeral port will be allocated. If you need a specific port then you can bind it explicitly which is needed for bootp for instance. But in the most simple case bind is not needed and you get the ephemeral port.

The peer will see this port in the UDP header because in there is both the source and destination port.

As a side note this mechanism is the same for TCP clients. When they do a call to connect() unless the socket was bind to a specific port, an ephemeral port will be allocated by the clients kernel and that one will be used for the lifetime of the connection.

The ephemeral ports are usually in a specific range, there is kindof a pool of ports for UDP and TCP. The kernel usually has a mechanism to take from the pool starting from the beginning and gradually incrementing till the end is reached upon which he'll start from the beginning. Skipping ports that are still in use of course. It is called the ephemeral port range, and it is specific to the os.

how to change/view ephemeral port range in windows machines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM