linux 做UDP服务器与客户机实验的时候接受错误
电脑上模拟了两台机器:服务器,客户机。现在两台机器能通信。但是问题如下:
客户机向服务器发送了个字符串,服务器能完全收到,但是有错误返回并且错误代码显示错误代码14:bad address;紧接着反过来向客户机回送信息,就完全收不到了,而且错误代码显示错误22:invalid argument.
客户机代码:
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#define SERV_PORT 10000
#define MAXLINE 80
void do_cli(FILE *fp,int sockfd,struct sockaddr *pservaddr,socklen_t servlen)
{
int n;
char sendline[MAXLINE],recvline[MAXLINE+1];
/*if(connect(sockfd,(struct sockaddr *)pservaddr,servlen)==-1)
{
perror("connect error");
exit(1);
}*/
while(fgets(sendline,MAXLINE,fp)!=NULL)
{
if(n= sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)pservaddr,sizeof(struct sockaddr))>0)
printf("write successfully\n");
n=recvfrom(sockfd,recvline,strlen(recvline),0,(struct sockaddr *)pservaddr,sizeof(struct sockaddr));
if(n==-1)
{
perror("read error");
exit(1);
}
recvline[n]=0;
fputs(recvline,stdout);
}
}
int main(int argc,char **argv)
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0) /* zifuxingdizhibianchenwangluodizhi */
{
printf("[%s] is not a valid IPaddress\n",argv[1]);
exit(1);
}
sockfd=socket(AF_INET,SOCK_DGRAM,0);
printf("socket successfully\n");
do_cli(stdin,sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
return 0;
}
服务器代码:
#include "apue.h"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/socket.h>
#define MAXLINE 80
#define SERV_PORT 10000
struct sockaddr_in servaddr,cliaddr;
void do_serv(int sockfd)
{
int n;
char recve[MAXLINE];
for( ; ; )
{
n=recvfrom(sockfd,recve,sizeof(recve),0,(struct sockaddr *)&cliaddr,(int *)sizeof(cliaddr));
if(n==-1)
{
printf("recive error\n");
printf("errno is %d:\n",errno);
}
fputs(recve,stdout);
n=sendto(sockfd,recve,3,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
if(n==-1)
{
printf("send error\n");
printf("errno is %d:\n",errno);
}
}
}
int main()
{
int sockfd;
/* struct sockaddr_in servaddr,cliaddr;*/
sockfd=socket(AF_INET,SOCK_DGRAM,0);
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERV_PORT);
if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1)
{
perror("bind error\n");
exit(1);
}
do_serv(sockfd);
}
------解决方案--------------------
if(n= sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)pservaddr,sizeof(struct sockaddr_in))>0)
而且你都传入servlen了,为什么不用?
n=recvfrom(sockfd,recvline,sizeof(recvline),0,(struct sockaddr *)pservadd