UDP是永固数据报协议,与TCP协议功能相同,我们在进行qq聊天的时候使用的就是UDP协议,下面学习啦小编给大家介绍下Linux如何使用UDP进行广播消息的发送与接收,一起来了解下吧。
[cpp] view plaincopy
// 发送端
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
cout《《“socket error”《
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.。。”《
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[] = {“abcdef”};
int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);
if(ret《0)
{
cout《《“send error.。。。”《
}
else
{
printf(“ok ”);
}
}
return 0;
}
[cpp] view plaincopy
// 接收端
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
// 绑定地址
struct sockaddr_in addrto;
bzero(&addrto, 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;
bzero(&from, sizeof(struct sockaddr_in));
from.sin_family = AF_INET;
from.sin_addr.s_addr = htonl(INADDR_ANY);
from.sin_port = htons(6000);
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
cout《《“socket error”《
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.。。”《
return false;
}
if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)
{
cout《《“bind error.。。”《
return false;
}
int len = sizeof(sockaddr_in);
char smsg[100] = {0};
while(1)
{
//从广播地址接受消息
int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
if(ret《=0)
{
cout《《“read error.。。。”《
}
else
{
printf(“%s/t”, smsg);
}
sleep(1);
}
return 0;
}
上面就是Linux使用DUP发送接收广播消息的方法介绍了,为DUP配置命令,还可实现更多的功能,DUP协议还有资源消耗小,处理速度快的优点,广泛应用于视频、音频的传送。