C # Use UdpClient to send broadcast messages

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.