UdpClient Class
The UdpClient
class provides simple methods for sending and receiving UDP datagrams.
Namespace: System.Net.Sockets
Assembly: System.Net.Sockets.dll
Syntax
public class UdpClient : IDisposable
{
// Constructors
public UdpClient();
public UdpClient(int port);
public UdpClient(IPEndPoint localEP);
public UdpClient(string hostname, int port);
public UdpClient(AddressFamily family);
// Properties
public bool Active { get; }
public IPEndPoint Client { get; set; }
public bool EnableBroadcast { get; set; }
public int Ttl { get; set; }
public bool DontFragment { get; set; }
public short MulticastLoopback { get; set; }
// Methods
public void Close();
public void Connect(string hostname, int port);
public void Connect(IPEndPoint remoteEP);
public void Connect(IPAddress address, int port);
public void DropMulticastGroup(IPAddress multicastAddr);
public void DropMulticastGroup(IPAddress multicastAddr, int ifindex);
public void JoinMulticastGroup(IPAddress multicastAddr);
public void JoinMulticastGroup(IPAddress multicastAddr, int ifindex);
public void Send(byte[] dgram, int bytes);
public void Send(byte[] dgram, int bytes, string hostname, int port);
public Task SendAsync(byte[] datagram, int bytes);
public Task SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint);
public Task ReceiveAsync();
public Task SendAsync(ReadOnlyMemory buffer, IPEndPoint remoteEndPoint);
// etc.
}
Remarks
The UdpClient
class encapsulates a UDP socket and provides higher‑level methods for sending and receiving data. It is designed for simple scenarios; for full control use the Socket
class.
UDP is connectionless and does not guarantee delivery, ordering, or duplicate protection of packets.
Examples
Sending a Datagram
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main()
{
using var client = new UdpClient();
var remoteEndPoint = new IPEndPoint(IPAddress.Parse("239.0.0.222"), 11000);
var message = Encoding.UTF8.GetBytes("Hello UDP!");
client.Send(message, message.Length, remoteEndPoint);
Console.WriteLine("Message sent.");
}
}
Receiving Datagrams Asynchronously
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Receiver
{
static async Task Main()
{
using var udp = new UdpClient(11000);
Console.WriteLine("Listening for UDP datagrams on port 11000...");
while (true)
{
var result = await udp.ReceiveAsync();
var msg = Encoding.UTF8.GetString(result.Buffer);
Console.WriteLine($"> Received from {result.RemoteEndPoint}: {msg}");
}
}
}