当前位置: 技术问答>linux和unix
请问这个程序(UDP)什么地方错了
来源: 互联网 发布时间:2016-10-09
本文导语: //udpser.c #include /* These are the usual header files */ #include #include /* for bzero() */ #include /* for close() */ #include #include #include #include #define PORT 1234 /* Port that will ...
//udpser.c
#include /* These are the usual header files */
#include
#include /* for bzero() */
#include /* for close() */
#include
#include
#include
#include
#define PORT 1234 /* Port that will be opened */
#define MAXDATASIZE 100 /* Max number of bytes of data */
main()
{
int sockfd; /* socket descriptors */
struct sockaddr_in server; /* server's address information */
struct sockaddr_in client; /* client's address information */
int sin_size;
int num;
char msg[MAXDATASIZE]; /* buffer for message */
/* Creating UDP socket */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
/* handle exception */
perror("Creating socket failed.");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr = htonl (INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) {
/* handle exception */
perror("Bind error.");
exit(1);
}
sin_size=sizeof(struct sockaddr_in);
while (1) {
num = recvfrom(sockfd,msg,MAXDATASIZE,0,(struct sockaddr *)&client,&sin_size);
if (num h_addr); /*he->h_addr passes "*he"'s info to "h_addr" */
sendto(fd, argv[2], strlen(argv[2]),0,(struct sockaddr *)&server,sizeof(struct sockaddr));
while (1) {
int len;
numbytes=recvfrom(fd,buf,MAXDATASIZE,0,(struct sockaddr *)&reply,&len);
if(numbytes == -1)
{ /* calls recvfrom() */
printf("recvfrom() errorn");
exit(1);
}
if (len != sizeof(struct sockaddr) || memcmp((const void *)&server, (const void *)&reply,len) != 0) {
printf("Receive message from other server.n");
continue;
}
buf[numbytes]='';
printf("Server Message: %sn",buf); /* it prints server's welcome message */
break;
}
close(fd); /* close fd */
}
操作过程:打开两个终端,
终端1运行 ./udpser
终端2运行 ./udpcli 127.0.0.1 hello
然后,
终端1显示:You got a message (hello) from 127.0.0.1
终端2显示:recvfrom() error
(如果一切正常的话,终端2应该显示:Server Message: Welcome to my server. 这是为什么?)
这是一个UDP的服务器程序和客户端程序(一本书上的例子),
不知为什么,客户端向服务器传信息成功了,服务器向客户端传信息却失败了
请大家帮我看一下这个程序到底是什么地方错了,还是我的电脑(Ubuntu 10.04)设置错了
|
int len; //这里没有初始化