System.Net.Sockets
UdpClient.UdpEndpoint

UdpClient.UdpEndpoint Property

Gets or sets the remote endpoint to which UDP datagrams are sent. (Inherited from UdpClient)

public System.Net.EndPoint UdpEndpoint { get; set; }

Remarks

The UdpEndpoint property specifies the destination for outgoing UDP datagrams. If you want to receive datagrams from any remote host, you can use the parameterless constructor of the UdpClient class and then bind to a specific local port using the Client.Bind method.

If you use a constructor that specifies a remote endpoint, this property is automatically initialized to that endpoint. If you use a constructor that binds to a local port, you can set this property later to specify the destination for outgoing datagrams.

When you use the Send method without specifying a remote endpoint, the UdpClient uses the endpoint specified in the UdpEndpoint property.

Properties

Name Description
AddressFamily Gets the address family of the endpoint.
Address Gets or sets the IP address of the endpoint.
Port Gets or sets the port number of the endpoint.

Examples

// Example demonstrating setting the UdpEndpoint
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class UdpEndpointExample
{
    public static async Task SendAndReceiveAsync()
    {
        // Create a UdpClient to send datagrams to a specific endpoint
        using (UdpClient sender = new UdpClient())
        {
            // Define the remote endpoint
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);

            // Set the UdpEndpoint property
            sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            sender.Client.Bind(remoteEP); // Bind to the local endpoint for receiving
            sender.Connect(remoteEP); // Connect to the remote endpoint for sending


            // Message to send
            string message = "Hello, UDP!";
            byte[] sendBytes = Encoding.ASCII.GetBytes(message);

            // Send the datagram
            int bytesSent = await sender.SendAsync(sendBytes, sendBytes.Length);
            Console.WriteLine($"Sent {bytesSent} bytes to {remoteEP}");

            // Create another UdpClient to receive datagrams
            using (UdpClient receiver = new UdpClient(11000)) // Listen on port 11000
            {
                Console.WriteLine("Listening for datagrams...");

                // Receive datagram
                UdpReceiveResult result = await receiver.ReceiveAsync();
                string receivedMessage = Encoding.ASCII.GetString(result.Buffer);
                IPEndPoint remote = result.RemoteEndPoint;

                Console.WriteLine($"Received '{receivedMessage}' from {remote}");
            }
        }
    }

    public static void Main(string[] args)
    {
        SendAndReceiveAsync().GetAwaiter().GetResult();
    }
}

See Also