head.h
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
客户端(接收方)
#include "head.h"
#define errlog(err) do{perror(err); exit(1);} while(0)
#define N 32
int main(int argc, const char *argv[])
{
int sockfd;
struct sockaddr_in groupcastaddr;
socklen_t len = sizeof(groupcastaddr);
char buf[N] = {0};
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
errlog("fail to socket");
}
struct ip_mreq mreq;
socklen_t mreq_len = sizeof(mreq);
mreq.imr_multiaddr.s_addr = inet_addr(argv[1]);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, mreq_len);
groupcastaddr.sin_family = AF_INET;
groupcastaddr.sin_port = htons(atoi(argv[2]));
groupcastaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr*)&groupcastaddr, len) < 0)
{
errlog("fail to bind");
}
while(1)
{
recvfrom(sockfd, buf, N, 0, (struct sockaddr*)&groupcastaddr, &len);
if(strncmp(buf, "quit", 4) == 0)
{
break;
}
printf("--> %s \n", buf);
}
close(sockfd);
return 0;
}
服务器(发送方)
#include "head.h"
#define errlog(err) do{perror(err); exit(1);} while(0)
#define N 32
int main(int argc, const char *argv[])
{
int sockfd;
struct sockaddr_in groupcastaddr;
socklen_t len = sizeof(groupcastaddr);
char buf[N] = {0};
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
errlog("fail to socket");
}
groupcastaddr.sin_family = AF_INET;
groupcastaddr.sin_port = htons(atoi(argv[2]));
groupcastaddr.sin_addr.s_addr = inet_addr(argv[1]);
while(1)
{
fgets(buf, N, stdin);
buf[strlen(buf) - 1] = '\0';
sendto(sockfd, buf, N, 0, (struct sockaddr*)&groupcastaddr, len);
}
close(sockfd);
return 0;
}