Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsureness about passing EndPoint to Socket.ReceiveFrom()

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

like image 804
haiyyu Avatar asked Feb 07 '12 16:02

haiyyu


1 Answers

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 :-)
like image 89
Krzysztof Kozielczyk Avatar answered Nov 19 '22 16:11

Krzysztof Kozielczyk