请教个问题,关于广播包的发送和接收广播包的发送方地址问题
小弟,有两个问题:
1.发送广播包,但是sendto总是返回-1.
2.recvfrom接收到广播包后,struct sockaddr * from 参数打印出来from.sin_addr.s_addr为0.
程序如下:
第一个问题程序片段:
udp_socket = socket( AF_INET , SOCK_DGRAM , 0 ) ;
if ( udp_socket != ERROR )
{
return;
}
// addr.sin_len = sizeof( struct sockaddr ) ;
addr.sin_family = AF_INET ;
addr.sin_port = htons( 0 ) ;
addr.sin_addr.s_addr = htonl ( INADDR_ANY ) ;
if( bind ( udp_socket , ( struct sockaddr *)&addr , sizeof( struct sockaddr ) ) == ERROR )
{
udp_socket = ERROR ;
return;
}
// to.sin_len = sizeof( struct sockaddr ) ;
to.sin_family = AF_INET ;
len = MAX_UDP_SEND_BUFFER ;
setsockopt(udp_socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(len));
setsockopt(udp_socket, SOL_SOCKET, SO_BROADCAST, (char*)&on, sizeof(on));
.......
ret = sendto( udp_socket, (char *)&Reportcmd, sizeof(Reportcmd), 0, (struct sockaddr *)&to, sizeof(struct sockaddr)) ;
//返回-1!!!!!!
第二段程序:
ret = recvfrom(sock, (char*)&cmd, sizeof(cmd), 0, (struct sockaddr *)&from, &addrlen);
if(ret <= 0 )
{
continue;
}
//打印了printf("from %d\n",from.sin_addr.s_addr);这里总是0
.......
ret = sendto(sock, (char*)&anscom, sizeof(RVSRespCommand), 0, (struct sockaddr*)&from, sizeof(struct sockaddr));//这里也发送不出去,返回总是-1.
[解决办法]
ret = sendto( udp_socket, (char *)&Reportcmd, sizeof(Reportcmd), 0, (struct sockaddr *)&to, sizeof(struct sockaddr)) ;
这里地址to你还没有赋值吧,广播IP地址端口号都没有呢,你这个没设好,下面的肯定都不行。