Chinaunix首页 | 论坛 | 博客
  • 博客访问: 267745
  • 博文数量: 113
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1044
  • 用 户 组: 普通用户
  • 注册时间: 2015-02-15 16:09
文章分类

全部博文(113)

文章存档

2016年(5)

2015年(108)

我的朋友

分类: C/C++

2015-08-26 14:43:24

UDP server   nonblocking

点击(此处)折叠或打开

  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <arpa/inet.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <string.h>
  9. #include <stdlib.h>

  10. int main()
  11. {
  12.     int sock;
  13.     int addr_len, bytes_read;
  14.     char recv_data[1024];
  15.     struct sockaddr_in server_addr , client_addr;


  16.     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
  17.         perror("Socket");
  18.         exit(1);
  19.     }

  20.     server_addr.sin_family = AF_INET;
  21.     server_addr.sin_port = htons(5000);

  22.     server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

  23.     bzero(&(server_addr.sin_zero),8);


  24.     if (bind(sock,(struct sockaddr *)&server_addr,
  25.              sizeof(struct sockaddr)) == -1)
  26.     {
  27.         perror("Bind");
  28.         exit(1);
  29.     }

  30.     addr_len = sizeof(struct sockaddr);

  31.     printf("\nUDPServer Waiting for client on port 5000");
  32.     fflush(stdout);

  33.     while (1)
  34.     {

  35.         bytes_read = recvfrom(sock,recv_data,1024,0, (struct sockaddr *)&client_addr, &addr_len); // <---- Here is the problem


  36.         recv_data[bytes_read] = '\0';

  37.         printf("\n(%s , %d) said : ",inet_ntoa(client_addr.sin_addr),
  38.                ntohs(client_addr.sin_port));
  39.         printf("%s", recv_data);
  40.         fflush(stdout);

  41.     }
  42.     return 0;
  43. }

阅读(808) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~