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
相关文章