Unicast (point-to-point) communication means that a single source node in the network sends packets to a single node.
In broadcast communication, the network layer provides services to send packets from one node to all other nodes.
Broadcast allows you to send data to each machine on the local subnet. The disadvantage of broadcast is that if multiple processes send broadcast data, the network will be blocked.
1. Server
Code
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net. Sockets;
Using System. Net;
Using System. Threading;
Namespace _ 5. _ 2 _ broadcast communication
{
Class Program
{
Static void Main (string [] args)
{
Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
S. SetSocketOption (SocketOptionLevel. Socket, SocketOptionName. Broadcast, true );
Byte [] buffer = Encoding. Unicode. GetBytes ("Hello World ");
IPEndPoint iep1 = new IPEndPoint (IPAddress. Broadcast, 4567); // 255.255.255.255
Int I = 0;
While (true)
{
Console. WriteLine ("broadcasting {0}", I ++. ToString ());
S. SendTo (buffer, iep1 );
Thread. Sleep (5000 );
}
}
}
}
For UPD, there is a specific broadcast address-broadcast bandwidth limit 255. broadcast data should be sent here.
The destination IP address of a broadcast message is a special IP address called a broadcast address.
A broadcast address consists of an IP address network prefix and a full host suffix. For example, 192.168.1.255 is the broadcast address of the network 192.169.1.0;
130.168.255.255 is the broadcast address of the network 130.168.0.0.
If a message is sent to an IP address (255.255.255.255.255), all the Internet-connected computers in the world can receive the message theoretically.
However, this is not the case. Generally, the packet is discarded on the router and only broadcast in the gossip network. Therefore, the effect is the same as that of sending messages to the broadcast address of the primary network.
Broadcast Communication. The broadcast option SO_BROADCAST must be enabled.
2. Client
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Socket m_s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 4567);
EndPoint ep = (EndPoint)iep;