1. #include "net.h"
    2. int main (void)
    3. {
    4. int fd = -1;
    5. struct sockaddr_in sin;
    6. /* 1. 创建socket fd */
    7. if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { //udp程序
    8. perror ("socket");
    9. exit (1);
    10. }
    11. /* 2. 允许绑定地址快速重用 */
    12. int b_reuse = 1;
    13. setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));
    14. /*加入多播组*/
    15. struct ip_mreq mreq;
    16. bzero(&mreq, sizeof(mreq));
    17. mreq.imr_multiaddr.s_addr = inet_addr("235.10.10.3");
    18. mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    19. setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq, sizeof(mreq));
    20. /*2. 绑定 */
    21. /*2.1 填充struct sockaddr_in结构体变量 */
    22. bzero (&sin, sizeof (sin));
    23. sin.sin_family = AF_INET;
    24. sin.sin_port = htons (SERV_PORT); //网络字节序的端口号
    25. /* 让服务器程序能绑定在任意的IP上 */
    26. #if 1
    27. sin.sin_addr.s_addr = htonl (INADDR_ANY);
    28. #else
    29. if (inet_pton (AF_INET, SERV_IP_ADDR, (void *) &sin.sin_addr) != 1) {
    30. perror ("inet_pton");
    31. exit (1);
    32. }
    33. #endif
    34. /*2.2 绑定 */
    35. if (bind (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
    36. perror ("bind");
    37. exit (1);
    38. }
    39. char buf[BUFSIZ];
    40. struct sockaddr_in cin;
    41. socklen_t addrlen = sizeof (cin);
    42. printf ("\nmulticast demo started!\n");
    43. while (1) {
    44. bzero (buf, BUFSIZ);
    45. if (recvfrom (fd, buf, BUFSIZ - 1, 0, (struct sockaddr *) &cin, &addrlen) < 0) {
    46. perror ("recvfrom");
    47. continue;
    48. }
    49. char ipv4_addr[16];
    50. if (!inet_ntop (AF_INET, (void *) &cin.sin_addr, ipv4_addr, sizeof (cin))) {
    51. perror ("inet_ntop");
    52. exit (1);
    53. }
    54. printf ("Recived from(%s:%d), data:%s", ipv4_addr, ntohs (cin.sin_port), buf);
    55. if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    56. printf ("Client(%s:%d) is exiting!\n", ipv4_addr, ntohs (cin.sin_port));
    57. }
    58. }
    59. close (fd);
    60. return 0;
    61. }