套接字编程:sendto始终以errno 22(EINVAL)失败

时间:2010-10-24 01:12:13

标签: c sockets udp sendto

我总是没有发送任何字节,使用此代码的错误值为22(EINVAL,Invalid Argument)。 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);
}

3 个答案:

答案 0 :(得分:11)

你给出了错误的地址大小。 addr实际上是struct sockaddr_in,而不是struct sockaddr

将sendto的最后一个参数更改为sizeof(address)

答案 1 :(得分:5)

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

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

答案 2 :(得分:-1)

你有:

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

由于sizeof(addr) == 4(或8),请使用sizeof(*addr)