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);
datagrambyte array containing the data to be sent.bytesdatagram buffer.socketFlagsremoteEPsizedatagram buffer.dgrambyte array containing the data to be sent.The number of bytes sent to the Socket.
ArgumentNullExceptiondatagram is null.ArgumentOutOfRangeExceptionbytes is less than 0 or greater than the size of the datagram buffer.ObjectDisposedExceptionSocketExceptionNotSupportedExceptionSendTo 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.
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}");
}
}
}