简体   繁体   English

C ++通过UDP发送数据包但未接收到它

[英]C++ Send packet through UDP but not receiving it

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. 我当前正在从事一个项目,需要每秒将数据包广播到公共端口D88,但是客户端无法接收数据包。 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. 假设192.168.1.255的网络掩码是255.255.255.0,则192.168.1.255是广播地址。 From man ip(7) : man ip(7)

Datagrams to broadcast addresses can be only sent or received when the SO_BROADCAST socket flag is set. 仅当设置了SO_BROADCAST套接字标志时,才能发送或接收用于广播地址的数据报。

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 . 如果检查sendto的返回值,则必须为-1且errno == EACCESS Always check the return values. 始终检查返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM