关于将 EndPoint 传递给 Socket.ReceiveFrom() 的不确定性

发布于 2025-01-03 12:29:17 字数 519 浏览 4 评论 0原文

如果我执行以下操作:

byte[] buffer = new byte[1024];
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint remote = new IPEndPoint(IPAddress.Parse("12.34.56.78"), 1337);
sock.ReceiveFrom(buffer, ref remote);

ReceiveFrom 方法是否仅从正在传递的端点接收数据包?该文档说明如下:

对于无连接协议,ReceiveFrom 将读取第一个 接收到本地网络缓冲区的排队数据报。

这是否意味着传递的 EndPoint 仅用于存储数据包来自的主机的 EndPoint,并且根本不影响 ReceiveFrom 方法的行为?如果是这样,为什么需要将其作为“ref”而不是“out”传递?

If I do something like this:

byte[] buffer = new byte[1024];
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint remote = new IPEndPoint(IPAddress.Parse("12.34.56.78"), 1337);
sock.ReceiveFrom(buffer, ref remote);

Will the ReceiveFrom method only receive packets from the endpoint that is being passed? The documentation states the following:

With connectionless protocols, ReceiveFrom will read the first
enqueued datagram received into the local network buffer.

Does that mean that the passed EndPoint is only used for storing the EndPoint of the host the packet has come from and does not affect the ReceiveFrom method's behaviour at all? If so, why does it need to be passed as "ref" instead of "out"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆头 2025-01-10 12:29:17

请注意,ReceiveFrom方法是recvfrom WinSock 函数。该函数采用一个指向 sockaddr 结构的指针,该结构是可选的,并在调用方分配/释放。

考虑到这一点,我有一些理论为什么 EndPoint 作为 ref 传递而不是 out

  1. 也许是为了与 WinSock 函数保持一致,< code>EndPoint 由调用者分配,因此由 ref 传递。
  2. 也许 EndPoint 在某些时候被认为是可选参数,但这从未实现(我检查过,它必须是非空的)。
  3. 也许对于某些协议,有通过 EndPoint 参数传递的处理方向。甚至可能是未来的协议:-)

Note that ReceiveFrom method is a managed wrapper for recvfrom WinSock function. This function takes a pointer to sockaddr structure that is optional and allocated/deallocated on the caller side.

With that in mind I have a few theories why is the EndPoint passed as ref and not out:

  1. Maybe for the consistency with WinSock function the EndPoint is allocated by the caller and therefore passed by ref.
  2. Maybe EndPoint was at some point considered to be an optional parameter, but this was never implemented (I checked, it must be non-null).
  3. Maybe for some protocols there are processing directions passed through the EndPoint parameter. Maybe even future protocols :-)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文