简体   繁体   English

DatagramSocket.Receive没有设置端口

[英]DatagramSocket.Receive without port set

I've recently started to learn about socket usage, more specifically in Java. 我最近开始学习有关套接字的用法,尤其是在Java中。

In this link is shown a simple client-server UDP application. 此链接中显示了一个简单的客户端-服务器UDP应用程序。

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? 我的问题是:当此数据报套接字对象调用receive没有设置端口时,客户端如何通过receive()方法接收响应?

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. 客户端通过空构造函数初始化其DatagramSocket ,该构造函数将套接字绑定到通配符地址上的某个可用端口(以未指定的方式选择)。 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. 如果需要特定端口,则可以显式绑定该端口,例如,对于bootp来说是必需的。 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. 对等方将在UDP标头中看到此端口,因为其中既有源端口,也有目标端口。

As a side note this mechanism is the same for TCP clients. 附带说明一下,此机制对于TCP客户端是相同的。 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. 当他们调用connect()除非套接字绑定到特定端口时,客户端内核将分配一个临时端口,并且该临时端口将用于连接的整个生命周期。

The ephemeral ports are usually in a specific range, there is kindof a pool of ports for UDP and TCP. 临时端口通常在特定范围内,其中存在用于UDP和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. 它称为临时端口范围,特定于os。

how to change/view ephemeral port range in windows machines 如何在Windows机器中更改/查看临时端口范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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