广播通信
广播:可以把数据发送给本地子网上的每个机器。
如果多个进程都发送广播数据,网络就会阻塞
对于UDP来说,存在一个特定的广播地址,255.255.255.255
发送方程序在创建套接字后使用setsockopt函数打开SO_BROADCAST选项,然后设置广播地址255.255.255.255,向端口号4567不断发送广播数据。
发送代码如下:
SOCKET s = ::socket(AF_INET,SOCK_DGRAM,0); //有效的SO_BROADCAST选项 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_addr = INADDR_BROADCAST; bcast.sin_port = htons(4567); //发送广播 printf("开始向4567发送广播数据...\n"); char sz[] = "this is just a test.\n"; while(TRUE) { ::sendto(s,sz,strlen(sz),0,(sockaddr*)&bcast,sizeof(bcast)); ::Sleep(5000); }
接收方代码:
SOCKET s = ::socket(AF_INET,SOCK_DGRAM,0); //绑定一个本地地址,指明广播端口号 SOCKADDR_IN sin; sin.sin_family = AF_INET; sin.sin_addr.S_un.S_addr = INADDR_ANY; sin.sin_port = ::ntohs(4567); if(::bind(s,(sockaddr*)&sin,&sizeof(sin))==SOCKET_ERROR) { printf("bind() failed!\n"); return; } //接收广播 printf("开始在4567接收广播数据...\n"); char sz[256]; while(TRUE) { int nRet = ::recvfrom(s,sz,256,0,(sockaddr*)&addRemote,&nLen); if(nRet>0) { sz[nRet] = '\0'; printf(sz); } }
完整源代码如下:(可运行)
sender.cpp:
///////////////////////////////////////// // sender.cpp文件 #include "initsock.h" #include "stdio.h" #include <windows.h> CInitSock theSock; void main() { SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); // 有效SO_BROADCAST选项 BOOL bBroadcast = TRUE; ::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL)); // 设置广播地址,这里的广播端口号(电台)是4567 SOCKADDR_IN bcast; bcast.sin_family = AF_INET; bcast.sin_addr.s_addr = INADDR_BROADCAST; // ::inet_addr("255.255.255.255"); bcast.sin_port = htons(4567); // 发送广播 printf(" 开始向4567端口发送广播数据... \n \n"); char sz[] = "This is just a test. \r\n"; while(TRUE) { ::sendto(s, sz, strlen(sz), 0, (sockaddr*)&bcast, sizeof(bcast)); ::Sleep(5000); } } /* ::send(s, sz, strlen(sz), 0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = ntohs(3333); addr.sin_addr.S_un.S_addr = ADDR_ANY; if(::bind(s, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { printf(" bind() failed \n"); return; } */
recver.cpp:
///////////////////////////////////////////////////// // recver.cpp文件 #include "initsock.h" #include "stdio.h" #include <windows.h> CInitSock theSock; void main() { SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0); // 首先要绑定一个本地地址,指明广播端口号 SOCKADDR_IN sin; sin.sin_family = AF_INET; sin.sin_addr.S_un.S_addr = INADDR_ANY; sin.sin_port = ::ntohs(4567); if(::bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) { printf(" bind() failed \n"); return; } // 接收广播 printf(" 开始在4567端口接收广播数据... \n\n"); SOCKADDR_IN addrRemote; int nLen = sizeof(addrRemote); char sz[256]; while(TRUE) { int nRet = ::recvfrom(s, sz, 256, 0, (sockaddr*)&addrRemote, &nLen); if(nRet > 0) { sz[nRet] = '\0'; printf(sz); } } }
运行结果: