为什么我需要 UDP 上的源端口

Why do I need source port on UDP

当我使用 TCP 时,我需要目标端口(以便能够 "talk" 到另一台主机上的其他进程)和源端口(因为 TCP 是面向连接的,所以我会将数据发送回源,例如ack、seq 等)。 另一方面,无连接的UDP也需要源端口。

这是为什么? (我不需要发回数据)

您不需要,但仍有可能发回响应(这实际上非常有用),但是如 RCF 768 中所述

Source Port is an optional field, when meaningful, it indicates the port of the sending process, and may be assumed to be the port to which a reply should be addressed in the absence of any other information. If not used, a value of zero is inserted.

https://www.rfc-editor.org/rfc/rfc768

可能有两个原因。

首先,接收者经常需要回复,为此提供一个标准工具很有用。

其次,您可能有多个接口(网卡)并使用源地址,您决定必须使用其中的哪个来发出数据包。

我想补充一下这里的答案。除了简单地知道要回复什么之外,源端口还可以属于 list of well-known port numbers。这些端口指定在 UDP(或 TCP!)数据包中封装的数据类型。

例如源端口530表示该数据包包含一个Remote Procedure Call, and 520 indicates a Routing Information Protocol数据包。