views:

30

answers:

1

When I want to received UDP datagrams asynchronously, I write call BeginReceiveFrom of a System.Net.Sockets.Socket class. The BeginReceiveFrom method expects an Endpoint as the remoteEP parameter.

public IAsyncResult BeginReceiveFrom (
  byte[] buffer,
  int offset,
  int size,
  SocketFlags socketFlags,
  ref EndPoint remoteEP,
  AsyncCallback callback,
  Object state
)

This Method starts an asynchronous receive and cannot return any result in remoteEP since it returns immediately. Is this parameter for a kind of filtering or will it be modified on receive completion?

In the receive handler I call EndReceiveFrom, where I also have to pass a reference to an Enpoint object as the endPoint parameter.

public int EndReceiveFrom (
  IAsyncResult asyncResult,
  ref EndPoint endPoint
)

The EndReceiveFrom indicates with this Endpoint object the sender of the UDP frame. Why must I pass a remoteEP to the BeginReceiveFrom and can I avoid this?

A: 

There's no overloads that do not require an endpoint, but that doesn't mean you have to specify specific endpoints. You can specify any ip address as the remoteEP.

EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

EndReceiveFrom expects a pass by ref variable that will be populated by the method call itself. You can instantiate the endPoint similarly.

EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);

After the call is made, simply ignore the value of receivedFromEP if you do not need it.

P.Brian.Mackey
So what is the remoteEP parameter in BeginReceiveFrom for? Why do I create an IPEndPoint that's ignored anyway?
harper
I do not have any documentation to provide a definite answer to your question, perhaps somebody else does. My guess is that it has to do with binding to network interfaces, security, and convention. Oftentimes applications send data bidirectionally, so it makes sense to know where data came from. You will likely have more than one client as well so a seperation of data and maybe even ordering of packets could be necessary (subsets of TCP functionality). I believe not needing any client information is more the exception to the rule. So it makes sense to populate the EndPoint by default.
P.Brian.Mackey