#include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char const *argv[]) { // 1.创建套接字 int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("sockfd"); return -1; } // 2.多播 struct ip_mreq mul; mul.imr_multiaddr.s_addr = inet_addr("224.0.0.2"); mul.imr_interface.s_addr = htonl(INADDR_ANY); setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mul, sizeof(mul)); // 3.绑定 struct sockaddr_in myaddr; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(8000); myaddr.sin_addr.s_addr = htonl(INADDR_ANY); int ret = 0; ret = bind(sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr)); if (ret != 0) { perror("bind"); return -1; } // 4.接受数据 char buf[1500] = ""; char ip[16] = ""; unsigned short port = 0; struct sockaddr_in srcaddr; socklen_t len = sizeof(srcaddr); while (1) { bzero(buf, sizeof(buf)); bzero(&srcaddr, len); recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&srcaddr, &len); inet_ntop(AF_INET, (void *)&srcaddr.sin_addr, ip, 16); port = ntohs(srcaddr.sin_port); printf("%s/%hu:%s\n", ip, port, buf); } // 5.关闭套接字 close(sockfd); return 0; }
标签:多播,UDP,myaddr,组内,srcaddr,sockfd,sizeof,buf,addr From: https://www.cnblogs.com/mengyaoli/p/17900061.html