This topic has not yet been rated Rate this topic

UdpClient Class

Provides User Datagram Protocol (UDP) network services.

System.Object
  System.Net.Sockets.UdpClient

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
public class UdpClient : IDisposable

The UdpClient type exposes the following members.

  Name Description
Public method UdpClient Initializes a new instance of the UdpClient class.
Public method UdpClient(AddressFamily) Initializes a new instance of the UdpClient class.
Public method UdpClient(Int32) Initializes a new instance of the UdpClient class and binds it to the local port number provided.
Public method UdpClient(IPEndPoint) Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.
Public method UdpClient(Int32, AddressFamily) Initializes a new instance of the UdpClient class and binds it to the local port number provided.
Public method UdpClient(String, Int32) Initializes a new instance of the UdpClient class and establishes a default remote host.
Top
  Name Description
Protected property Active Gets or sets a value indicating whether a default remote host has been established.
Public property Available Gets the amount of data received from the network that is available to read.
Public property Client Gets or sets the underlying network Socket.
Public property DontFragment Gets or sets a Boolean value that specifies whether the UdpClient allows Internet Protocol (IP) datagrams to be fragmented.
Public property EnableBroadcast Gets or sets a Boolean value that specifies whether the UdpClient may send or receive broadcast packets.
Public property ExclusiveAddressUse Gets or sets a Boolean value that specifies whether the UdpClient allows only one client to use a port.
Public property MulticastLoopback Gets or sets a Boolean value that specifies whether outgoing multicast packets are delivered to the sending application.
Public property Ttl Gets or sets a value that specifies the Time to Live (TTL) value of Internet Protocol (IP) packets sent by the UdpClient.
Top
  Name Description
Public method AllowNatTraversal Enables or disables Network Address Translation (NAT) traversal on a UdpClient instance.
Public method BeginReceive Receives a datagram from a remote host asynchronously.
Public method BeginSend(Byte(), Int32, AsyncCallback, Object) Sends a datagram to a remote host asynchronously. The destination was specified previously by a call to Connect.
Public method BeginSend(Byte(), Int32, IPEndPoint, AsyncCallback, Object) Sends a datagram to a destination asynchronously. The destination is specified by a EndPoint.
Public method BeginSend(Byte(), Int32, String, Int32, AsyncCallback, Object) Sends a datagram to a destination asynchronously. The destination is specified by the host name and port number.
Public method Close Closes the UDP connection.
Public method Connect(IPEndPoint) Establishes a default remote host using the specified network endpoint.
Public method Connect(IPAddress, Int32) Establishes a default remote host using the specified IP address and port number.
Public method Connect(String, Int32) Establishes a default remote host using the specified host name and port number.
Protected method Dispose Releases the unmanaged resources used by the UdpClient and optionally releases the managed resources.
Public method DropMulticastGroup(IPAddress) Leaves a multicast group.
Public method DropMulticastGroup(IPAddress, Int32) Leaves a multicast group.
Public method EndReceive Ends a pending asynchronous receive.
Public method EndSend Ends a pending asynchronous send.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method JoinMulticastGroup(IPAddress) Adds a UdpClient to a multicast group.
Public method JoinMulticastGroup(Int32, IPAddress) Adds a UdpClient to a multicast group.
Public method JoinMulticastGroup(IPAddress, Int32) Adds a UdpClient to a multicast group with the specified Time to Live (TTL).
Public method JoinMulticastGroup(IPAddress, IPAddress) Adds a UdpClient to a multicast group.
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Receive Returns a UDP datagram that was sent by a remote host.
Public method Send(Byte(), Int32) Sends a UDP datagram to a remote host.
Public method Send(Byte(), Int32, IPEndPoint) Sends a UDP datagram to the host at the specified remote endpoint.
Public method Send(Byte(), Int32, String, Int32) Sends a UDP datagram to a specified port on a specified remote host.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Explicit interface implemetation Private method IDisposable.Dispose Infrastructure. Releases all resources used by the UdpClient.
Top

The UdpClient class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. You do, however, have the option of establishing a default remote host in one of the following two ways:

  • Create an instance of the UdpClient class using the remote host name and port number as parameters.

  • Create an instance of the UdpClient class and then call the Connect method.

You can use any of the send methods provided in the UdpClient to send data to a remote device. Use the Receive method to receive data from remote hosts.

Note Note

Do not call Send using a host name or IPEndPoint if you have already specified a default remote host. If you do, UdpClient will throw an exception.

UdpClient methods also allow you to send and receive multicast datagrams. Use the JoinMulticastGroup method to subscribe a UdpClient to a multicast group. Use the DropMulticastGroup method to unsubscribe a UdpClient from a multicast group.

The following example establishes a UdpClient connection using the host name www.contoso.com on port 11000. A small string message is sent to two separate remote host machines. The Receive method blocks execution until a message is received. Using the IPEndPoint passed to Receive, the identity of the responding host is revealed.


// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(11000);
    try{
         udpClient.Connect("www.contoso.com", 11000);

         // Sends a message to the host to which you have connected.
         Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

         udpClient.Send(sendBytes, sendBytes.Length);

         // Sends a message to a different host using optional hostname and port parameters.
         UdpClient udpClientB = new UdpClient();
         udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

         //IPEndPoint object will allow us to read datagrams sent from any source.
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

         // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
         string returnData = Encoding.ASCII.GetString(receiveBytes);

         // Uses the IPEndPoint object to determine which of these two hosts responded.
         Console.WriteLine("This is the message you received " +
    	                              returnData.ToString());
         Console.WriteLine("This message was sent from " +
                                     RemoteIpEndPoint.Address.ToString() +
                                     " on their port number " +
                                     RemoteIpEndPoint.Port.ToString());

          udpClient.Close();
          udpClientB.Close();

          }  
       catch (Exception e ) {
                  Console.WriteLine(e.ToString());
        }


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • SocketPermission  

    To establish an outgoing connection or accept an incoming request.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
Broadcasting in Windows 7
In Windows 7, if you're trying to broadcast a message, you can send to 255.255.255.255 BUT(!) you must bind the UdpClient to the local IP of each adapter in your machine in turn BEFORE you send your data.
Win 7/XP UDP Broadcast differences
Just a note on UDP broadcast on Windows 7. Maybe this is documented somewhere but it cost me a couple of days: $0$0 $0 $0UdpClient client = new UdpClient(_localPort, AddressFamily.InterNetwork);$0 $0 $0
IPEndPoint groupEp = new IPEndPoint(IPAddress.Broadcast, _remotePort);
            
client.Connect(groupEp);

client.Send(_findBytes, _findBytes.Length);
client.Close();

This code will work on XP and send broadcast UDP messages. On Windows 7, no packets are sent (confirmed with Wireshark). Fix for Windows 7 is to restrict the broadcast range:

IPAddress destIp = IPAddress.Parse("192.168.1.255");

IPEndPoint groupEp = new IPEndPoint(destIp, _remotePort);

The packets are now sent.

$0
$0$0 $0
PowerShell Example
#This constructor arbitrarily assigns the local port number.
$udpobject = new-Object system.Net.Sockets.Udpclient(11000)

Try {    
    $udpobject.Connect("Hostname",11000)
    
    #Sends a message to the host to which you have connected.
    $a = new-object system.text.asciiencoding
    $byte = $a.GetBytes("Is anybody there?")
    [void]$udpobject.Send($byte,$byte.length)

    #Sends a message to a different host using optional hostname and port parameters.
    $udpobjectb = new-Object system.Net.Sockets.Udpclient
    [void]$udpobjectb.Send($byte,$byte.length,"AlternateHostname",11000)
    
    #IPEndPoint object will allow us to read datagrams sent from any source.
    $remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
    
    #Blocks until a message returns on this socket from a remote host.
    $receivebytes = $udpobject.Receive([ref]$remoteendpoint)
    [string]$returndata = $a.GetString($receivebytes)
     
    #Uses the IPEndPoint object to determine which of these two hosts responded.
    Write-Host "This is the message you received: $($returndata.ToString())"
    Write-Host "This message was sent from: $($remoteendpoint.address.ToString()) on their port number: $($remoteendpoint.Port.ToString())"

    $udpobject.Close()
    $udpobjectb.close()
    }
Catch {
    Write-Warning "$($Error[0])"
    }