完善资料让更多小伙伴认识你,还能领取20积分哦, 立即完善>
/* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */ if ((sock_group = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { rt_kprintf("Socket errorn"); /* 释放接收用的数据缓冲 */ rt_free(recv_data); return; } memset(&server_addr,0,sizeof(server_addr)); /* 初始化服务端地址 */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(37889); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock_group, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { /* 绑定地址失败 */ rt_kprintf("Bind errorn"); /* 释放接收用的数据缓冲 */ rt_free(recv_data); return; } struct ip_mreq ipmr; ipmr.imr_interface.s_addr = htonl(INADDR_ANY); ipmr.imr_multiaddr.s_addr = inet_addr("239.255.255.250"); int loop=1; if(-1==setsockopt(sock_group, IPPROTO_IP, IP_MULTICAST_LOOP,& loop, sizeof(loop))) { rt_kprintf("IPPROTO_IP, IP_MULTICAST_LOOP"); } if(setsockopt(sock_group, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&ipmr, sizeof(ipmr))) { rt_kprintf("IP_ADD_MEMBERSHIPrn"); return; } else { rt_kprintf("IP_ADD_MEMBERSHIP OK!rn"); } addr_len = sizeof(struct sockaddr); rt_kprintf("UDPServer_group Waiting for client on port 37889...n"); while (1) { /* 从sock中收取最大BUFSZ - 1字节数据 */ bytes_read = recvfrom(sock_group, recv_data, BUFSZ - 1, 0, (struct sockaddr *)&client_addr, &addr_len); /* UDP不同于TCP,它基本不会出现收取的数据失败的情况,除非设置了超时等待 */ recv_data[bytes_read] = ' |