代码之家  ›  专栏  ›  技术社区  ›  dc.

套接字编程:sendto总是失败,错误号为22(EINVAL)

  •  4
  • dc.  · 技术社区  · 14 年前

    我总是收到没有字节发送,错误码为22(EINVAL,无效参数)。这个 destination_host 是在别处设置的,并且已知是有效的,所以我真的不知道发生了什么。 MAXMSGSIZE -Wall -Werror -pedantic

    char *data_rec;
    u_int data_len;
    
    int sockfd;
    uint16_t *ns;
    struct sockaddr_in address;
    struct sockaddr *addr;
    
    char *ip;
    
    int i;
    int errno;
    int bytes_sent;
    
    data_len = MAXMSGSIZE;
    data_rec = malloc(sizeof(char)*MAXMSGSIZE);
    ns = malloc(MAXMSGSIZE*sizeof(uint16_t));
    ip = malloc(MAXMSGSIZE*sizeof(char));
    
    data_rec = "some random test stuff";
    
    sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sockfd<0) {
        printf("socket() failed\n");
    }
    
    inet_ntop(AF_INET,destination_host->h_addr,ip,MAXMSGSIZE);
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(theirPort);
    address.sin_addr.s_addr = (unsigned long)ip;
    
    addr = (struct sockaddr*)&address;
    bind(sockfd,addr,sizeof(address));
    /*Convert the message to uint16_t*/
    for(i=0; i<MAXMSGSIZE; i++) {
        ns[i] = htons(data_rec[i]);
    }
    
    
    /* send the message */
    bytes_sent = sendto(sockfd, ns, data_len, MSG_DONTWAIT, addr, sizeof(addr));
    if(bytes_sent == -1) {
        printf("Error sending: %i\n",errno);
    }
    
    3 回复  |  直到 8 年前
        1
  •  11
  •   nos    14 年前

    你给的地址大小不对。 addr struct sockaddr_in ,不是 struct sockaddr .

    sizeof(address)

        2
  •  5
  •   SimonJ    14 年前

    inet_ntop 可能不是你想要的-它从 网络 演示 格式(即“1.2.3.4”)。尝试:

    address.sin_addr.s_addr = *((unsigned long *)destination_host->h_addr);
    
        3
  •  -1
  •   Jonathan Leffler    8 年前

    bytes_sent = sendto(sockfd, ns, data_len, MSG_DONTWAIT, addr, sizeof(addr));
    

    因为 sizeof(addr) == 4 (或8),使用 sizeof(*addr) .