How Linux implements the transmission of UDP broadcast messages

  
                

UDP is the permanent datagram protocol. It has the same function as the TCP protocol. We use the UDP protocol when doing qq chat. The following is a small series to introduce how Linux uses UDP to send and receive broadcast messages. Get up and get to know it.

[cpp] view plaincopy

//transmitting end

#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;

//Set the socket Word is broadcast type,

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);

//Send a message from a broadcast address

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
Previous12Next Total 2 Pages

Copyright © Windows knowledge All Rights Reserved