发送方
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <pthread.h>
#define PORT 33333
int main()
{
int socfd = socket(AF_INET,SOCK_DGRAM,0);
struct ip_mreqn val;
val.imr_multiaddr.s_addr=inet_addr("225.0.0.0");
val.imr_address.s_addr=INADDR_ANY;
val.imr_ifindex= if_nametoindex("ens33");
setsockopt(socfd,IPPROTO_IP,IP_MULTICAST_IF,&val,sizeof(val));
char buf[100];
struct sockaddr_in cli_addr;
cli_addr.sin_family=AF_INET;
cli_addr.sin_addr.s_addr=inet_addr("225.0.0.0");
cli_addr.sin_port=htons(PORT);
while(1)
{
printf("请输入内容\n");
scanf("%s",buf);
getchar();
sendto(socfd,buf,strlen(buf),0,(struct sockaddr *)(&cli_addr),sizeof(cli_addr));
perror("sendto");
}
}
接收方
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <pthread.h>
#define PORT 33333
int main()
{
int socfd = socket(AF_INET,SOCK_DGRAM,0);
struct ip_mreqn val;
val.imr_multiaddr.s_addr=inet_addr("225.0.0.0");
val.imr_address.s_addr=INADDR_ANY;
val.imr_ifindex= if_nametoindex("ens33");
setsockopt(socfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&val,sizeof(val));
struct sockaddr_in self;
self.sin_family=AF_INET;
self.sin_addr.s_addr=INADDR_ANY;
self.sin_port=htons(PORT);
bind(socfd,(struct sockaddr *)(&self),sizeof(self));
char buf[100];
struct sockaddr_in cli_addr;
int len = sizeof(cli_addr);
while(1)
{
memset(buf,0,100);
recvfrom(socfd,buf,100,0,(struct sockaddr *)(&cli_addr),&len);
printf("IP:%s PORT:%hu\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
printf("%s\n",buf);
perror("recvfrom");
}
}