First, write a client to receive messages. The new UdpClient (11000) listens to port 11000 in Udp mode and receives any messages sent to port 11000.
Code:
UdpClient udpClient = new UdpClient(11000);
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
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();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Then write a Udp server.
Code:
UdpClient udpClient = new UdpClient(11001);
try
{
udpClient.Connect(IPAddress.Parse("192.168.0.255"), 11000);
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody thereA?");
udpClient.Send(sendBytes, sendBytes.Length);
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
192.168.0.255 is your intranet broadcast address, and 11000 is the client port.
The broadcast address is obtained through your subnet mask. For example, if your gateway is 192.168.0.1 and the mask is 255.255.255.0, your broadcast address is 192.168.0.255.