日期:2014-05-16  浏览次数:20771 次

udp socket 协议问题,大家帮我找找原因,出现的错误是 recv: Bad address
运行结果:
[root@heiying udp]# ./udp_client
recv: Bad address
[root@heiying udp]# 




[root@heiying udp]# ./udp_server
receive from client is A



服务端 udp_server
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
int i,byte;
char char_recv,char_send;

server_sockfd = socket(AF_INET, SOCK_DGRAM, 0);

server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9734;
server_len = sizeof(server_address);

bind(server_sockfd, (struct sockaddr *)&server_address, server_len);

client_len=sizeof(client_address);
for(i=0,char_send='1';i<5;i++,char_send++)
{
if((byte=recvfrom(server_sockfd,&char_recv,1,0,(struct sockaddr *)&client_address,(socklen_t *)&client_len))==-1)
{
perror("recv");
exit(EXIT_FAILURE);
}
printf("receive from client is %c\n",char_recv);

if((byte=sendto(server_sockfd,&char_send,1,0,(struct sockaddr *)&client_address,(socklen_t)client_len))==-1)
{
perror("send");
exit(EXIT_FAILURE);
}
}
//shutdown(client_sockfd,2);
shutdown(server_sockfd,2);
}




客户端 udp_client

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int sockfd;
int len,cl_len;
struct sockaddr_in address,cl_addr;
int result;
int i,byte;
char char_recv,char_send;
  if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))==-1)
{
perror("socket");
exit(EXIT_FAILURE);
}

  address.sin_family = AF_INET; //设置服务器主机信息
  address.sin_addr.s_addr = inet_addr("127.0.0.1");
  address.sin_port = 9734;
// cl_addr.sin_family = AF_INET;
// cl_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// cl_addr.sin_port = 9739;


  len = sizeof(address);
// cl_len= sizeof (cl_addr);
// bind(sockfd, (struct sockaddr *)&cl_addr, len);

for(i=0,char_send='A';i<5;i++,char_send++)
{
if((byte=sendto(sockfd,&char_send,1,0,(struct sockaddr *)&address,(socklen_t)len)) == -1 )
{
perror("sendto");
exit(EXIT_FAILURE);
}
if((byte=recvfrom(sockfd,&char_recv,1,0,(struct sockaddr *)&address,(socklen_t *)len))==-1)
{
perror("recv"); //这句会打印出来
exit(EXIT_FAILURE);
}
printf("receive from client is %c\n",char_recv);

/* if((byte=recv(sockfd,&char_recv,1,0))==-1)
{
perror("recv");
exit(EXIT_FAILURE);
}
printf("receive from server %c\n",char_recv);
*/}
  close(sockfd);
  exit(0);
}


------解决方案--------------------
探讨

谢谢啦,那请问为什么第五个参数要为NULL ????? 什么意思啊 ????

------解决方案--------------------
应该是 第五个参数为NULL时,第6个参数被忽略
------解决方案-----------