廣播通訊

廣播:能夠把數據發送給本地子網上的每一個機器。windows

若是多個進程都發送廣播數據,網絡就會阻塞網絡

對於UDP來講,存在一個特定的廣播地址,255.255.255.255socket

 

發送方程序在建立套接字後使用setsockopt函數打開SO_BROADCAST選項,而後設置廣播地址255.255.255.255,向端口號4567不斷髮送廣播數據。函數

發送代碼以下:this

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); }

接收方代碼:spa

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); } }

完整源代碼以下:(可運行)code

sender.cpp:blog

/////////////////////////////////////////
// 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); } } }

運行結果:it

相關文章
相關標籤/搜索