开发者

i am unable to connetct udp server and udp client in this code?

UDP_SERVER

int main()
  {
   int sockfd,clilen;
   char arr[20];
   struct sockaddr_in serv_add,cliaddr;


   if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
        printf("error");
      bzero((char *)&serv_add,sizeof(serv_add));
    serv_add.sin_family=AF_INET;
    serv_add.sin_port=htons(6060);
    serv_add.sin_addr.s_addr=inet_addr("127.0.0.1");


   if(bind(sockfd,(struct sockaddr *)&serv_add,sizeof(serv_add))<0)
        printf("bind error");    

  //while(1)
    {

     //recv(sockfd,&arr,10,0);
     clilen=sizeof(cliaddr);
     recvfrom(sockfd,arr,10,0,(struct sockaddr *)&cliaddr,&clilen);
     printf("%s",arr);      
    }
close(sockfd);
return 0;
}

UDP_CLIENT

int main()
  {
   int sockfd;
   struct sockaddr_in servaddr,cliaddr;

  sockfd=socket(AF_INET,SOCK_DGRAM,0);

  bzero((char *)&servaddr,sizeof(servaddr));
  servaddr.sin_family=AF_INET;
  servaddr.sin_port=6060;
  servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");

  bzero((char *)&cliaddr,sizeof(cliaddr));
  cliaddr.sin_family=AF_INET;
  cliaddr.sin_port=htons(0);
  cliaddr.sin_开发者_StackOverflow中文版addr.s_addr=htonl(INADDR_ANY); 
  //printf("%s")  

  if(bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr))<0)
    printf("error");

  sendto(sockfd,"subh.singh",10,0,(struct sockaddr *)&servaddr,sizeof(servaddr));
  close(sockfd);
  return 0;
  }


In the client you forgot htons:

servaddr.sin_port=6060; /* Wrong. */
servaddr.sin_port = htons(6060); /* Right. */
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜