Unsureness about passing EndPoint to Socket.ReceiveFrom()

淺唱寂寞╮ 提交于 2020-01-03 11:32:45

问题


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"?


回答1:


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 :-)


来源:https://stackoverflow.com/questions/9180328/unsureness-about-passing-endpoint-to-socket-receivefrom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!