Linux如何實(shí)現(xiàn)UDP廣播消息的傳輸
Linux如何實(shí)現(xiàn)UDP廣播消息的傳輸
UDP是永固數(shù)據(jù)報(bào)協(xié)議,與TCP協(xié)議功能相同,我們?cè)谶M(jìn)行qq聊天的時(shí)候使用的就是UDP協(xié)議,下面學(xué)習(xí)啦小編給大家介紹下Linux如何使用UDP進(jìn)行廣播消息的發(fā)送與接收,一起來了解下吧。
[cpp] view plaincopy
// 發(fā)送端
#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;
//設(shè)置該套接字為廣播類型,
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);
//從廣播地址發(fā)送消息
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;
//設(shè)置該套接字為廣播類型,
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發(fā)送接收廣播消息的方法介紹了,為DUP配置命令,還可實(shí)現(xiàn)更多的功能,DUP協(xié)議還有資源消耗小,處理速度快的優(yōu)點(diǎn),廣泛應(yīng)用于視頻、音頻的傳送。