UdpClient.EndReceive Method (IAsyncResult, IPEndPoint)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Ends a pending asynchronous receive.

Namespace:   System.Net.Sockets
Assembly:  System (in System.dll)

public byte[] EndReceive(
	IAsyncResult asyncResult,
	ref IPEndPoint remoteEP


Type: System.IAsyncResult

An IAsyncResult object returned by a call to BeginReceive.

Type: System.Net.IPEndPoint

The specified remote endpoint.

Return Value

Type: System.Byte[]

If successful, the number of bytes received. If unsuccessful, this method returns 0.

Exception Condition

asyncResult is null.


asyncResult was not returned by a call to the BeginReceive method.


EndReceive was previously called for the asynchronous read.


An error occurred when attempting to access the underlying Socket. See the Remarks section for more information.


The underlying Socket has been closed.

This method blocks until the operation is complete.

To perform this operation synchronously, use the Receive method.

The following code example uses BeginSend to complete an asynchronous receive of a server response.

public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
  UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
  IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

  Byte[] receiveBytes = u.EndReceive(ar, ref e);
  string receiveString = Encoding.ASCII.GetString(receiveBytes);

  Console.WriteLine("Received: {0}", receiveString);
  messageReceived = true;

public static void ReceiveMessages()
  // Receive a message and write it to the console.
  IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
  UdpClient u = new UdpClient(e);

  UdpState s = new UdpState();
  s.e = e;
  s.u = u;

  Console.WriteLine("listening for messages");
  u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

  // Do some work while we wait for a message. For this example,
  // we'll just sleep
  while (!messageReceived)

.NET Framework
Available since 2.0
Return to top