server:
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,ProtocolType.Udp);
//255.255.255.255
IPEndPoint iep1 =
new IPEndPoint(IPAddress.Broadcast, 9050);
IPEndPoint iep2 =
new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(hostname);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep1);
sock.SendTo(data, iep2);
sock.Close();
client:
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive…");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sock.Close();
C#广播程序
前言
在网络编程中,通过广播和多播可以实现发送端发送一个数据包,有多个接收端接收的情况。
广播
由于Tcp是有连接的,所以不能用来发送广播消息。发送广播消息,必须用到Udp,Udp可以不用建立连接而发送消息。广播消息的目的IP地址是一种特殊IP地址,称为广播地址。广播地址由IP地址网络前缀加上全1主机后缀组成,如:192.168.1.255是192.169.1.0这个网络的广播地址;130.168.255.255是130.168.0.0这个网络的广播地址。向全部为1的IP地址(255.255.255.255)发送消息的话,那么理论上全世界所有的联网的计算机都能收得到了。但实际上不是这样的,一般路由器上设置抛弃这样的包,只在本地网内广播,所以效果和向本地网的广播地址发送消息是一样的。
C#中发送广播消息的过程如下,注意要调用SetSockOption函数,不然要抛出异常:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
//255.255.255.255
IPEndPoint iep1 =
new IPEndPoint(IPAddress.Broadcast, 9050);
IPEndPoint iep2 =
new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(hostname);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep1);
sock.SendTo(data, iep2);
sock.Close();
C#中接收广播消息的过程如下,没有什么特别的:
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep =
new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive…");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sock.Close();
Attentions:
1 广播可以由客户程序来通知子网内的服务程序,自己的位置。2 发送广播消息时指定的端口也是有作用的,接收端的Udp Socket如果Bind到此接口的话,就能够接收到消息。(如果不Bind的话,就能接收所有端口的消息??)
3 接收端接到的包中显示的远端IP地址是发送端的地址。就是说广播地址不会显示到一个包的源IP地址位置(LoopBack地址不会显示到包的目的IP地址位置)
4 可以用线程不停地发送和接收广播消息,确认两端的位置和证明自己的存在
来源http://blog.sina.com.cn/s/blog_4b6068cc0100ivix.html