利用广播可以一次将数据发送给本地子网上每个机器,实现1对多通信。对于UDP来说,存在特定的广播地址255.255.255.255,而这个地址上的端口可看作广播的波段。要实现广播需设置套接字选项SO_BROADCAST,之后发送端和接收端只需要分别调用sendto和recvfrom函数。广播只能用于本地,不会被路由器转发。试着用VC写了个简单的例子。
发送端代码:
#include <winsock2.h>
#pragma comment(lib,"WS2_32");
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
WORD sockVersion=MAKEWORD(2,2);
if(::WSAStartup(sockVersion,&wsadata)!=0)
return 0;
SOCKET s=::socket(AF_INET,SOCK_DGRAM,0);
bool bBroadcast=true;
setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char*)&bBroadcast,sizeof(bool));
SOCKADDR_IN bcast;
bcast.sin_family=AF_INET;
bcast.sin_addr.S_un.S_addr=INADDR_BROADCAST;
bcast.sin_port=htons(4567);
printf("begin to broadcast..\n");
char text[]="a simple test\n";
for(int i=0;i<5;++i)
{
sendto(s,text,strlen(text),0,(sockaddr*)&bcast,sizeof(bcast));
Sleep(100);
}
printf("press any key to exit..\n");
getchar();
return 0;
}
接收端
#include <winsock2.h>
#pragma comment(lib,"WS2_32");
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
WORD sockVersion=MAKEWORD(2,2);
if(::WSAStartup(sockVersion,&wsadata)!=0)
return 0;
SOCKET s=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(4567);
sin.sin_addr.S_un.S_addr=INADDR_ANY;
if(bind(s,(SOCKADDR *)&sin,sizeof(sin))==SOCKET_ERROR)
{
printf("failed to bind");
return 0;
}
printf("begin to recv broadcast msg..\n");
SOCKADDR_IN ser;
int nLen=sizeof(ser);
char buf[256];
while(1)
{
memset(buf,0,256);
int nRet=recvfrom(s,buf,256,0,(SOCKADDR*)&ser,&nLen);
if (nRet>0)
{
buf[nRet]='\n';
printf(buf);
}
}
return 0;
}