C语言 套接字编程:sendto 总是以 errno 22 (EINVAL) 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4006786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:46:57  来源:igfitidea点击:

Socket programming: sendto always fails with errno 22 (EINVAL)

csocketsudpsendto

提问by dc.

I am always getting no bytes sent, with an errno of 22 (EINVAL, Invalid Argument) with this code. The destination_hostis set elsewhere and known to be valid, so I really don't see what is going on. MAXMSGSIZEis 1000. No errors, or warnings. I am compiling with -Wall -Werror -pedantic

我总是没有发送任何字节,此代码的 errno 为 22(EINVAL,无效参数)。将destination_host在其他地方设置和已知是有效的,所以我真的不明白什么是要去。 MAXMSGSIZE是 1000。没有错误或警告。我正在编译-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);
}

回答by nos

You're giving the wrong size for the address. addris really a struct sockaddr_in, not a struct sockaddr.

您为地址提供了错误的大小。addr真的是一个struct sockaddr_in,不是一个struct sockaddr

Change the last parameter of sendto to sizeof(address)

把sendto的最后一个参数改成 sizeof(address)

回答by SimonJ

inet_ntopprobably isn't what you want - it converts from network(i.e. wire) format into presentationformat (i.e. "1.2.3.4"). Try:

inet_ntop可能不是您想要的 - 它从网络(即有线)格式转换为演示格式(即“1.2.3.4”)。尝试:

address.sin_addr.s_addr = *((unsigned long *)destination_host->h_addr);

回答by chao wang

You have:

你有:

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

Because sizeof(addr) == 4(or 8), use sizeof(*addr).

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