UdpClient.SendTo Method

Sends datagram packets to a specified remote host and port.

public virtual int SendTo(byte[] datagram, int bytes, SocketFlags socketFlags, EndPoint remoteEP); public virtual int SendTo(byte[] datagram, int bytes, SocketFlags socketFlags, IPEndPoint remoteEP); public virtual int SendTo(byte[] datagram, int size, EndPoint remoteEP); public virtual int SendTo(byte[] datagram, IPEndPoint remoteEP); public virtual int SendTo(byte[] dgram, int bytes, IPEndPoint remoteEP);

Parameters

datagram
A byte array containing the data to be sent.
bytes
The number of bytes to send from the datagram buffer.
socketFlags
A combination of SocketFlags values that specify options for the send operation. See SocketFlags for details.
remoteEP
An EndPoint that represents the remote host and port to which you want to send the datagram. This parameter can be an IPEndPoint.
size
The number of bytes to send from the datagram buffer.
dgram
A byte array containing the data to be sent.

Return Value

The number of bytes sent to the Socket.

Exceptions

ArgumentNullException
datagram is null.
ArgumentOutOfRangeException
bytes is less than 0 or greater than the size of the datagram buffer.
ObjectDisposedException
The UdpClient has been closed.
SocketException
An error occurred while accessing the socket. See SocketException for details.
NotSupportedException
The SocketFlags value is not supported.
Note: The SendTo method is used to send UDP datagrams to a specific remote host and port. If you do not specify a remote endpoint when you create the UdpClient, you must specify one when you call the SendTo method.

Example


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

public class UdpSendExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Creates a UdpClient for sending and receiving datagrams.
            using (UdpClient udpClient = new UdpClient())
            {
                // You can optionally bind to a local port if you need to receive responses.
                // udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, 11000));

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

                // Remote endpoint: IP address and port of the destination.
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11001);

                Console.WriteLine($"Sending UDP datagram to {remoteEP.Address}:{remoteEP.Port}");

                // Sends a datagram to the specified endpoint.
                int bytesSent = udpClient.SendTo(datagram, datagram.Length, remoteEP);

                Console.WriteLine($"Successfully sent {bytesSent} bytes.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}