问题
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:
- Maybe for the consistency with WinSock function the
EndPointis allocated by the caller and therefore passed byref. - Maybe
EndPointwas at some point considered to be an optional parameter, but this was never implemented (I checked, it must be non-null). - Maybe for some protocols there are processing directions passed through the
EndPointparameter. Maybe even future protocols :-)
来源:https://stackoverflow.com/questions/9180328/unsureness-about-passing-endpoint-to-socket-receivefrom