server.c
#include<errno.h>
#include<semaphore.h>
#include<string.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<signal.h>
#include<pthread.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<net/if.h>
#define SERVER_PORT 8000
#define MAXLINE 1500
#define GROUP "239.0.0.2"
#define CLIENT_PORT 9000
int main(){
struct sockaddr_in serveraddr,clientaddr;
int sockfd;
socklen_t clientlen;
char ipstr[INET_ADDRSTRLEN];
char buf[MAXLINE];
ssize_t len;
struct ip_mreqn group;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
serveraddr.sin_port=htons(SERVER_PORT);
bind(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
inet_pton(AF_INET,GROUP,&group.imr_multiaddr);
inet_pton(AF_INET,"0.0.0.0",&group.imr_address);
group.imr_ifindex=if_nametoindex("eno16777736");
setsockopt(sockfd,IPPROTO_IP,IP_MULTICAST_IF,
&group,sizeof(group));
bzero(&clientaddr,sizeof(clientaddr));
clientaddr.sin_family=AF_INET;
inet_pton(AF_INET,GROUP,&clientaddr.sin_addr.s_addr);
clientaddr.sin_port=htons(CLIENT_PORT);
while(fgets(buf,sizeof(buf),stdin)){
len=strlen(buf);
sendto(sockfd,buf,len,0,(struct sockaddr*)&clientaddr,sizeof(clientaddr));
}
close(sockfd);
return 0;
}
client.c
#include<errno.h>
#include<semaphore.h>
#include<string.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<signal.h>
#include<pthread.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<net/if.h>
#define SERVER_PORT 8000
#define CLIENT_PORT 9000
#define GROUP "239.0.0.2"
#define MAXLINE 4096
int main(int argc,char* argv[]){
struct sockaddr_in serveraddr,clientaddr;
int confd;
char buf[MAXLINE];
ssize_t len;
struct ip_mreqn group;
confd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&clientaddr,sizeof(clientaddr));
clientaddr.sin_family=AF_INET;
inet_pton(AF_INET,"0,0,0,0",&clientaddr.sin_addr.s_addr);
clientaddr.sin_port=htons(CLIENT_PORT);
bind(confd,(struct sockaddr*)&clientaddr,sizeof(clientaddr));
inet_pton(AF_INET,GROUP,&group.imr_multiaddr);
inet_pton(AF_INET,"0.0.0.0",&group.imr_address);
group.imr_ifindex=if_nametoindex("eno16777736");
setsockopt(confd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&group,sizeof(group));
while(1){
len=recvfrom(confd,buf,sizeof(buf),0,NULL,0);
write(STDOUT_FILENO,buf,len);
}
close(confd);
return 0;
}