套接字编程:sendto始终因errno 22(EINVAL)而失败 [英] Socket programming: sendto always fails with errno 22 (EINVAL)
问题描述
我总是没有收到任何字节,此代码的错误号为22(EINVAL,无效参数). destination_host
设置在其他位置,并且已知有效,所以我真的不知道发生了什么. MAXMSGSIZE
是1000.没有错误或警告.我正在使用-Wall -Werror -pedantic
I am always getting no bytes sent, with an errno of 22 (EINVAL, Invalid Argument) with this code. The destination_host
is set elsewhere and known to be valid, so I really don't see what is going on. MAXMSGSIZE
is 1000. No errors, or warnings. I am compiling with -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);
}
推荐答案
您输入的地址大小错误. addr
实际上是struct sockaddr_in
,而不是struct sockaddr
.
You're giving the wrong size for the address. addr
is really a struct sockaddr_in
, not a struct sockaddr
.
将sendto的最后一个参数更改为sizeof(address)
Change the last parameter of sendto to sizeof(address)
这篇关于套接字编程:sendto始终因errno 22(EINVAL)而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!