.NET Documentation

System.Net.Sockets.UdpClient.Send Method

UdpClient.Send Method

Sends UDP data to a remote host. This is a convenience method that uses the default remote host and port if they have been set using the Connect method.

Overloads

Parameters

Parameter Type Description
datagram byte[] A byte array containing the data to send.
bytes int The number of bytes to send from the datagram array.

Return Value

The number of bytes sent to the socket.

Exceptions

Exception Type Condition
ArgumentNullException datagram is null.
SocketException An error occurred when attempting to send data to the socket.
ObjectDisposedException The UdpClient has been closed.

Remarks

The Send method sends UDP datagrams. If you have not previously called the Connect method, the Send method will throw a SocketException.

To send to a specific remote host and port without establishing a connection, use the SendTo method.

Note

UDP is a connectionless protocol. The Send method does not guarantee delivery of the datagram. You may need to implement your own reliability mechanisms if delivery is critical.

Example


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpSender
{
    public static void Main(string[] args)
    {
        try
        {
            // Define the remote endpoint (IP address and port)
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 11000;
            IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);

            // Create a UdpClient instance
            using (UdpClient udpClient = new UdpClient())
            {
                // Connect to the remote endpoint
                udpClient.Connect(remoteEndPoint);

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

                // Send the data
                int bytesSent = udpClient.Send(sendBytes, sendBytes.Length);

                Console.WriteLine($"Sent {bytesSent} bytes to {remoteEndPoint}.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}
            

Tip

For broadcasting messages, you can connect to the broadcast address (e.g., IPAddress.Broadcast) and use the Send method. Ensure your network configuration allows broadcasting.