局域网广播通信源代码

//recv  接收广播信息

void main(void)
{
 SOCKET s;
 sockaddr_in from,a;
 WSADATA wsdata;
 BOOL optval;
 //启动SOCKET库,版本为2.0
 WSAStartup(0x0202,&wsdata);
 optval=TRUE;
 //然后赋值给两个地址,一个用来绑定套接字,一个用来从网络上的广播地址接收消息;
 a.sin_family=AF_INET;
 a.sin_addr.s_addr=0;
 a.sin_port=htons(5050);

 from.sin_family=AF_INET;
 from.sin_addr.s_addr=INADDR_BROADCAST;
 from.sin_port=htons(5050);
 
 int fromlength=sizeof(SOCKADDR);
 //用UDP初始化套接字
 s=socket(AF_INET,SOCK_DGRAM,0);
   //设置该套接字为广播类型,
 setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char FAR *)&optval,sizeof(optval));
 bind(s,(sockaddr *)&a,sizeof(sockaddr_in));
 char buf[256];
 while(1)
 {//从广播地址接收消息,注意用来绑定的地址和接收消息的地址是不一样的
  recvfrom(s,buf,256,0,(struct sockaddr FAR *)&from,(int FAR *)&fromlength);
  Sleep(2000);
  printf("%s/n",buf);
  ZeroMemory(buf,256);
 }

 

//send 发送广播信息

main()
{
 SOCKET s;
 sockaddr_in addrto;
 WSADATA wsdata;
 BOOL bsocket;
 char *smsg="this is a test";
 //启动SOCKET库,版本为2.0
 WSAStartup(0x0202,&wsdata);
 
 s=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
 bsocket=TRUE;
    //然后赋值给地址,用来从网络上的广播地址接收消息;
 addrto.sin_family=AF_INET;
    addrto.sin_addr.s_addr=INADDR_BROADCAST;
 addrto.sin_port=htons(5050);
 bool opt=true;
 //设置该套接字为广播类型,
 setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char FAR *)&opt,sizeof(opt));
 int nlen=sizeof(addrto);
 while(1)
 {
  Sleep(1000);
  //从广播地址发送消息
  int ret=sendto(s,smsg,256,0,(sockaddr*)&addrto,nlen);
  if(ret==SOCKET_ERROR)
   cout<<WSAGetLastError()<<endl;
  else
  {  
   printf("ok"); 
  }
 }
}

你可能感兴趣的:(socket,struct,网络,null)