这两天很多人在问怎么样用SOCKET实现广播(BoardCast)
正好我做过这方面的程序,这里用最简单的代码写一个广播发送和接受的例子:
//////
//发送端程序
#include <stdio.h> #include <winsock.h>
int main(int argc, char* argv[]) { WSADATA wsaData; //指向WinSocket信息结构的指针 SOCKET sockListener; SOCKADDR_IN sin,saUdpServ; BOOL fBroadcast = TRUE; char sendBuff[1024]; int nSize; int ncount=0; if(WSAStartup(MAKEWORD( 1, 1 ), &wsaData )!=0)//进行WinSocket的初始化 { printf("Can't initiates windows socket!Program stop.\n");//初始化失败返回-1 return -1; } sockListener=socket(PF_INET,SOCK_DGRAM,0); setsockopt ( sockListener,SOL_SOCKET,SO_BROADCAST,
(CHAR *)&fBroadcast,sizeof ( BOOL )); sin.sin_family = AF_INET; sin.sin_port = htons(0); sin.sin_addr.s_addr = htonl(INADDR_ANY); if(bind( sockListener, (SOCKADDR *)&sin, sizeof(sin))!=0) { printf("Can't bind socket to local port!Program stop.\n");//初始化失败返回-1 return -1; } saUdpServ.sin_family = AF_INET; saUdpServ.sin_addr.s_addr = htonl ( INADDR_BROADCAST ); saUdpServ.sin_port = htons (7001);//发送用的端口,可以根据需要更改 nSize = sizeof ( SOCKADDR_IN ); while(1) { sprintf(sendBuff,"Message %d",ncount++); sendto ( sockListener,sendBuff, lstrlen (sendBuff), 0, (SOCKADDR *) &saUdpServ, sizeof ( SOCKADDR_IN )); printf("%s\n",sendBuff); } return 0; }
/////////////////////
//接收
#include <stdio.h> #include <winsock.h> #include <conio.h>
int main(int argc, char* argv[]) { WSADATA wsaData; //指向WinSocket信息结构的指针 SOCKET sockListener; SOCKADDR_IN sin,saClient; char cRecvBuff[1024]; int nSize,nbSize; int iAddrLen=sizeof(saClient); if(WSAStartup(MAKEWORD( 1, 1 ), &wsaData )!=0)//进行WinSocket的初始化 { printf("Can't initiates windows socket!Program stop.\n");//初始化失败返回-1 return -1; } sockListener=socket(AF_INET, SOCK_DGRAM,0); sin.sin_family = AF_INET; sin.sin_port = htons(7001);//发送端使用的发送端口,可以根据需要更改 sin.sin_addr.s_addr = htonl(INADDR_ANY); if(bind( sockListener, (SOCKADDR FAR *)&sin, sizeof(sin))!=0) { printf("Can't bind socket to local port!Program stop.\n");//初始化失败返回-1 return -1; } while(1) { nSize = sizeof ( SOCKADDR_IN ); if((nbSize=recvfrom (sockListener,cRecvBuff,1024,0,
(SOCKADDR FAR *) &saClient,&nSize))==SOCKET_ERROR) { printf("Recive Error"); break; } cRecvBuff[nbSize] = '\0'; printf("%s\n",cRecvBuff);
} return 0; } 
|