UdpClient.Receive(IPEndPoint) Method

Definition

Returns a UDP datagram that was sent by a remote host.

public byte[] Receive (ref System.Net.IPEndPoint? remoteEP);
public byte[] Receive (ref System.Net.IPEndPoint remoteEP);

Parameters

remoteEP
IPEndPoint

An IPEndPoint that represents the remote host from which the data was sent.

Returns

Byte[]

An array of type Byte that contains datagram data.

Exceptions

The underlying Socket has been closed.

An error occurred when accessing the socket.

Examples

The following example demonstrates the Receive method. The Receive method blocks execution until it receives a message. Using the IPEndPoint passed to Receive, the identity of the responding host is revealed.

 //Creates a UdpClient for reading incoming data.
 UdpClient receivingUdpClient = new UdpClient(11000);

 //Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
 try{

     // Blocks until a message returns on this socket from a remote host.
     Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

     string returnData = Encoding.ASCII.GetString(receiveBytes);

     Console.WriteLine("This is the message you received " +
                               returnData.ToString());
     Console.WriteLine("This message was sent from " +
                                 RemoteIpEndPoint.Address.ToString() +
                                 " on their port number " +
                                 RemoteIpEndPoint.Port.ToString());
 }
 catch ( Exception e ){
     Console.WriteLine(e.ToString());
 }

Remarks

The Receive method will block until a datagram arrives from a remote host. When data is available, the Receive method will read the first enqueued datagram and return the data portion as a byte array. This method populates the remoteEP parameter with the IPAddress and port number of the sender.

If you specify a default remote host in the Connect method, the Receive method will accept datagrams from that host only. All other datagrams will be discarded.

If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Note

If you intend to receive multicasted datagrams, do not call the Connect method prior to calling the Receive method. The UdpClient you use to receive datagrams must be created using the multicast port number.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

See also