发送端
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
int main()
{
char buf[100] = {0};
int fd = socket(AF_INET,SOCK_DGRAM, 0);
struct sockaddr_in toaddr;
toaddr.sin_family = AF_INET;
toaddr.sin_port = htons(8888);
toaddr.sin_addr.s_addr = inet_addr("224.10.10.10");
scanf("%s", buf);
sendto(fd, buf, sizeof(buf), 0, (struct sockaddr *)&toaddr,sizeof(toaddr));
}
接收端
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
int main()
{
char buf[100] = {0};
int len = sizeof(struct sockaddr);
struct sockaddr youaddr;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in peeraddr;
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr("224.10.10.10");
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,sizeof(mreq));
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(8888);
peeraddr.sin_addr.s_addr = INADDR_ANY;
bind(fd,(struct sockaddr *)&peeraddr, sizeof(peeraddr));
while(1)
{
recvfrom(fd,buf,sizeof(buf), 0, &youaddr, &len);
printf("recv is %s\n", buf);
}
}
组播主要是用来约束接收端,在数据接收之前,要将自己的ip加入到多播组中,然后再进行接收。
另: struct ip_mreq 这个结构体,存在于 <netinet/in.h>这个头文件中。
整理完毕