sendto() 向广播地址发包返回errno 13, Permission denied错误

http://blog.csdn.net/guanghua2_0beta/article/details/52483916

sendto() 向广播地址发包返回errno 13, Permission denied错误

 

sendto()向广播地址发包返回errno 13, Permission denied错误

原因:
没有设置socket的SO_BROADCAST属性。特别注意:SO_BROADCAST属性要单独设置,一般习惯setsockopt时同时设置多个属性,例如SO_BROADCAST|SO_REUSEADDR,虽然大部分情况下工作正常,但工作中还是遇到了同时设置不起作用的问题;
 
int ret;
int optval = 1;    
ret = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &optval,sizeof(int));
if(ret!=0)
{
    printf("setsockopt SO_BROADCAST error:%d, %s\n", errno, strerror(errno));
    close(sockfd);
    return -1;
}
ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval,sizeof(int));
if(ret!=0)
{
    close(sockfd);
    return -1;
}

 

posted @ 2016-09-21 00:16  LiuYanYGZ  阅读(3330)  评论(0编辑  收藏  举报