linux 广播问题errno==13定位

原因分析:

没有设置socket的广播SO_BROADCAST属性,或者设置失败却想当然的认为是成功。这时sendto数据返回-1,errno等于13.


1、设置SO_BROADCAST失败,windows上xp是可以成功的

    bool bOptVal= 1;
    int n = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char*)&bOptVal, sizeof(bool));



2、设置SO_BROADCAST成功

    int bOptVal= 1;
    int n = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char*)&bOptVal, sizeof(int));

 

// 附录:代码

#include <stdio.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int sock = 0;


    if (argc < 2) {
        printf("Usage: %s local_address destination_address\n", argv[0]);
        exit(1);
    }


    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock <= 0) {
        perror("socket");
        return -1;
    }


    int bOptVal= 1;
    int n = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char*)&bOptVal, sizeof(int));
    printf("setsockopt return %d !\n",n);


    struct sockaddr_in local_addr;
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(1234);
    local_addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sock, (struct sockaddr *) &local_addr, sizeof(local_addr));
    if (ret < 0) {
        perror("bind");
        return -1;
    }
    
    struct sockaddr_in remote_addr;
    remote_addr.sin_family = AF_INET;
    remote_addr.sin_port = htons(1234);
    remote_addr.sin_addr.s_addr = inet_addr(argv[2]);
    ret = sendto(sock, "blah", 4, 0, (struct sockaddr *)&remote_addr, sizeof(remote_addr));
    if (ret < 0) {
        printf("sendto() returned negative, errno: %d/%m\n", errno);
    }
    else {
        printf("sendto() returned %d\n", ret);        
    }


    return 0;
}

你可能感兴趣的:(linux,windows,struct,socket,XP)