I'm currently working on a project need to broadcast the data packet to a common port D88 for every second, but the client can not receive the data packet. I'm not sure I'm using the right way to send the packet.
int sockfdBroad;
struct sockaddr_in addrBroad;
swStat.packetBroadSent=0;
sockfdBroad=socket(AF_INET,SOCK_DGRAM,0);
bzero(&addrBroad,sizeof(addrBroad));
addrBroad.sin_family = AF_INET;
addrBroad.sin_addr.s_addr=inet_addr("192.168.1.255");
addrBroad.sin_port=htons(3464);
if ((cycles%1000)==0)
{
currenttime = getMicrosTimeStamp();
createTimePacket(bufferTime,currenttime,Odroid_Trigger);
sendto(sockfdBroad,bufferTime,PACKET_LENGTH_TIME,0,(struct sockaddr *)&addrBroad,sizeof(addrBroad));
swStat.packetBroadSent++;
}
Assuming that the netmask for 192.168.1.255 is 255.255.255.0, 192.168.1.255 is a broadcast address. From man ip(7)
:
Datagrams to broadcast addresses can be only sent or received when the
SO_BROADCAST
socket flag is set.
In other words, both the sender and the receiver must do:
int value = 1;
if(-1 == setsockopt(socket, SOL_SOCKET, SO_BROADCAST, &value, sizeof value))
// Handle error.
If you check the return value of sendto
it must be -1 and errno == EACCESS
. Always check the return values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.