Wednesday, November 23, 2005

UdpClient.Receive()

I have been exposed to System.Net.Sockets.UdpClient recently. One of its member functions is Receive(ref IPEndPoint). I was wondering why IPEndPoint was passed to the function as a reference (pointer to a pointer actually). So I downloaded the source code for the Mono project, thinking that it would give me a clue. There the object passed in is never used, but a new IPEndPoint created and it passed back to the calling function. This actually makes sense since the returned IPEndPoint contains the IP address of the party sending the UDP package. But why then not define Receive() as Receive(out IPEndPoint)? Thus making the intention clear.

In fact setting IPEndPoint as null before passing it into Receive() works fine.

P.s. It was not necessary for me to pull out the Mono source, the Reflector gave me the code just fine :)

public byte[] Receive(ref IPEndPoint remoteEP)
{
EndPoint point1;
if (this.m_CleanedUp)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
if (this.m_Family == AddressFamily.InterNetwork)
{
point1 = IPEndPoint.Any;
}
else
{
point1 = IPEndPoint.IPv6Any;
}
int num1 = this.Client.ReceiveFrom(this.m_Buffer, 0x10000, SocketFlags.None, ref point1);
remoteEP = (IPEndPoint) point1;
if (num1 < 0x10000)
{
byte[] buffer1 = new byte[num1];
Buffer.BlockCopy(this.m_Buffer, 0, buffer1, 0, num1);
return buffer1;
}
return this.m_Buffer;
}

No comments: