Socket编程:SENDTO总是失败,错误号22 [英] Socket programming: sendto always fails with errno 22

查看:9089
本文介绍了Socket编程:SENDTO总是失败,错误号22的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是得到这个code发送,22(无效参数)的错误号没有字节。在 destination_host 设置别处称为是有效的,所以我真的不明白是怎么回事。 MAXMSGSIZE 是1000没有错误,或警告。我与 -Wall -pedantic -Werror

编译

 的char * data_rec;
u_int DATA_LEN;INT的sockfd;
uint16_t *纳秒;
结构sockaddr_in的地址;
结构sockaddr *地址;字符* IP;INT I;
INT错误号;
INT bytes_sent;DATA_LEN = MAXMSGSIZE;
data_rec =的malloc(sizeof的(char)的* MAXMSGSIZE);
NS =的malloc(MAXMSGSIZE *的sizeof(uint16_t));
IP =的malloc(MAXMSGSIZE *的sizeof(字符));data_rec =一些随机测试的东西;的sockfd =插座(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
如果(的sockfd℃,){
    的printf(插座()失败\\ n);
}inet_ntop(AF_INET,destination_host-> h_addr,IP,MAXMSGSIZE);
memset的(安培;地址,0,sizeof的(地址));
address.sin_family = AF_INET;
address.sin_port = htons(theirPort);
address.sin_addr.s_addr =(无符号长)知识产权;地址=(结构sockaddr *)及地址;
绑定(的sockfd,地址,的sizeof(地址));
/ *转换为uint16_t消息* /
对于(i = 0; I< MAXMSGSIZE;我++){
    NS [I] = htons(data_rec [I]);
}
/ *发送消息* /
bytes_sent = SENDTO(的sockfd,NS,DATA_LEN,MSG_DONTWAIT,地址,的sizeof(地址));
如果(bytes_sent == -1){
    的printf(发送错误:%I \\ N,错误号);
}


解决方案

你给的地址错误的大小。 地址是一个真正的结构SOCKADDR_IN ,而不是结构sockaddr

中的sendto的最后一个参数更改为的sizeof(地址)

I am always getting no bytes sent, with an errno of 22 (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);
}

解决方案

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

Change the last parameter of sendto to sizeof(address)

这篇关于Socket编程:SENDTO总是失败,错误号22的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆