广播发送与接收
//发送端
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
using namespace std;
int main()
{
WSADATA wsaData;
short version = MAKEWORD(2,0);
WSAStartup(version,&wsaData);//初始化socket
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
cout<<"socket error"<<endl;
return false;
}
const int opt = 1;
//设置该套接字为广播类型,
int nb = 0;
nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
cout<<"set socket error..."<<endl;
return false;
}
struct sockaddr_in addrto;
bzero(&addrto, sizeof(struct sockaddr_in));
addrto.sin_family=AF_INET;
addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
addrto.sin_port=htons(6000);
int nlen=sizeof(addrto);
while(1)
{
sleep(1);
//从广播地址发送消息
char smsg[] = {"broadcast msg"};
int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);
if(ret<0)
{
cout<<"send error...."<<ret<<endl;
}
else
{
printf("ok ");
}
}
return 0;
}
//接收端
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
using namespace std;
int main()
{
WSADATA wsaData;
short version = MAKEWORD(2,0);
WSAStartup(version,&wsaData);//初始化socket
// 绑定地址
struct sockaddr_in addrto;
memset(&addrto, 0, sizeof(struct sockaddr_in));
addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = htonl(INADDR_ANY);
addrto.sin_port = htons(6000);
// 对端地址
struct sockaddr_in from;
memset(&from, 0, sizeof(struct sockaddr_in));
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
cout<<"socket error"<<endl;
return false;
}
const int opt = 1;
//设置该套接字为广播类型,
int nb = 0;
nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
cout<<"set socket error..."<<endl;
return false;
}
if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)
{
cout<<"bind error..."<<endl;
return false;
}
int len = sizeof(sockaddr_in);
char smsg[100] = {0};
while(1)
{
//从广播地址接受消息
int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,&len);
if(ret<=0)
{
cout<<"read error...."<<sock<<endl;
}
else
{
printf("%s\n", smsg);
}
}
return 0;
}