Using UDP Services
The UdpClient class communicates with network services using UDP. The properties and methods of the UdpClient class abstract the details of creating a Socket for requesting and receiving data using UDP.
UDP offers the advantages of simplicity and the ability to broadcast messages to multiple addresses at the same time. However, because the UDP protocol is a connectionless protocol, UDP datagrams sent to the remote endpoint are not guaranteed to arrive, nor are they guaranteed to arrive in the same sequence in which they are sent. Applications that use UDP must be prepared to handle missing and out-of-sequence datagrams.
To send a datagram using UDP, you must know the network address of the network device hosting the service you need and the UDP port number that the service uses to communicate. The Internet Assigned Numbers Authority (IANA) defines port numbers for common services (see www.iana.org/assignments/port-numbers). Services not on the IANA list can have port numbers in the range 1,024 to 65,535.
Special network addresses are used to support UDP broadcast messages on IP-based networks. The following discussion uses the IP version 4 address family used on the Internet as an example.
IP version 4 addresses use 32 bits to specify a network address. For class C addresses using a netmask of 255.255.255.0, these bits are separated into four octets. When expressed in decimal, the four octets form the familiar dotted-quad notation, such as 192.168.100.2. The first two octets (192.168 in this example) form the network number; the third octet (100) defines the subnet; and the final octet (2) is the host identifier.
Setting all the bits of an IP address to one, or 255.255.255.255, forms the limited broadcast address. Sending a UDP datagram to this address delivers the message to any host on that broadcast network. Because routers never forward messages sent to this address, only hosts on the connected network see these broadcasts.
Broadcasts can be directed to specific portions of a network by setting portions of the address to all ones. For example, to send a broadcast to all hosts on the network identified by IP addresses starting with 192.168, set the subnet and host portions of the address to all ones, as in 192.168.255.255. To limit the broadcast to a single subnet, set just the host portion to all ones, as in 192.168.100.255.
The UdpClient class can broadcast to any network broadcast address, but it cannot listen for broadcasts sent to the network. You must use the Socket class to listen for network broadcasts.
Broadcast addresses work when all the recipients are in a single network or when many clients need to receive the broadcast. When the recipients are a small portion of the network, the message should be sent to a multicast group, where only the clients that have joined the group will receive it. The IP addresses ranging from 224.0.0.2 to 244.255.255.255 are reserved as host group addresses. The IP number 224.0.0.0 is reserved, and 224.0.0.1 is assigned to the permanent group of all IP hosts.
The following example uses UdpClient to listen for UDP datagrams broadcast to the multicast address group 224.168.100.2 on port 11000. It receives a message string and writes the message to the console.
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class UDPMulticastListener
Private Shared GroupAddress As IPAddress = _
IPAddress.Parse("224.168.100.2")
Private Shared GroupPort As Integer = 11000
Private Shared Sub StartListener()
Dim done As Boolean = False
Dim listener As New UdpClient()
Dim groupEP As New IPEndPoint(GroupAddress, GroupPort)
Try
listener.JoinMulticastGroup(GroupAddress)
listener.Connect(groupEP)
While Not done
Console.WriteLine("Waiting for broadcast")
Dim bytes As Byte() = listener.Receive(groupEP)
Console.WriteLine("Received broadcast from {0} :" + _
ControlChars.Cr + " {1}" + ControlChars.Cr, _
groupEP.ToString(), _
Encoding.ASCII.GetString(bytes, 0, bytes.Length))
End While
listener.Close()
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub 'StartListener
' Entry point that delegates to C-style main Private Function.
Public Overloads Shared Sub Main()
System.Environment.ExitCode = _
Main(System.Environment.GetCommandLineArgs())
End Sub
Overloads Public Shared Function Main(args() As [String]) As Integer
StartListener()
Return 0
End Function 'Main
End Class 'UDPMulticastListener
[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPMulticastListener {
private static readonly IPAddress GroupAddress =
IPAddress.Parse("224.168.100.2");
private const int GroupPort = 11000;
private static void StartListener() {
bool done = false;
UdpClient listener = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try {
listener.JoinMulticastGroup(GroupAddress);
listener.Connect(groupEP);
while (!done) {
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive( ref groupEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes,0,bytes.Length));
}
listener.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args) {
StartListener();
return 0;
}
}
The following example uses a UdpClient to send UDP datagrams to the multicast address group 224.268.100.2, using port 11000. It sends the message string specified on the command line.
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class UDPMulticastSender
Private Shared GroupAddress As IPAddress = _
IPAddress.Parse("224.168.100.2")
Private Shared GroupPort As Integer = 11000
Private Shared Sub Send(message As [String])
Dim sender As New UdpClient()
Dim groupEP As New IPEndPoint(GroupAddress, GroupPort)
Try
Console.WriteLine("Sending datagram : {0}", message)
Dim bytes As Byte() = Encoding.ASCII.GetBytes(message)
sender.Send(bytes, bytes.Length, groupEP)
sender.Close()
Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub 'Send
' Entry point that delegates to C-style main Private Function.
Public Overloads Shared Sub Main()
System.Environment.ExitCode = _
Main(System.Environment.GetCommandLineArgs())
End Sub
Overloads Public Shared Function Main(args() As [String]) As Integer
Send(args(0))
Return 0
End Function 'Main
End Class 'UDPMulticastSender
[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPMulticastSender {
private static IPAddress GroupAddress =
IPAddress.Parse("224.168.100.2");
private static int GroupPort = 11000;
private static void Send( String message) {
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress,GroupPort);
try {
Console.WriteLine("Sending datagram : {0}", message);
byte[] bytes = Encoding.ASCII.GetBytes(message);
sender.Send(bytes, bytes.Length, groupEP);
sender.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args) {
Send(args[0]);
return 0;
}
}