服务端循环每秒发送一次消息
客户端负责接收并打印在终端上。
客户端需要显式的使用bind()绑定地址。
group_proto.h 定义协议
#ifndef __GROUP_PROTO_H__
#define __GROUP_PROTO_H__
//多播组 接收端口
//多播组IP地址是224~239之间,下面这个多播组的IP地址是随便设的
#define GROUP_IP "224.2.3.4" //多播组的IP地址
//被动端需要端口号
#define RCV_PORT 1314 //端口号
//数据类型
#define MAX_MSG 1024 //最大数据量
#endif
client.c 客户端--仅负责接收消息,并打印
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <stdlib.h>
#include <unistd.h>
#include "group_proto.h"
int main(void)
{
int udp_socket;
struct sockaddr_in myaddr;
struct ip_mreqn imr;
char *buf = NULL;
int cnt;
//1.设置套接字文件的文件描述符
udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == udp_socket) {
perror("socket()");
exit(1);
}
//2.为结构体sockaddr_in的变量的成员赋值
//被动端需要bind地址
myaddr.sin_family = AF_INET;
//RCV_PORT是group_proto.h文件定义的宏,是一个端口号
//htons htons是一个网络字节序转换函数,用于将一个16位无符号整数从主机字节序转换为网络字节序。
myaddr.sin_port = htons(RCV_PORT);
//inet_aton函数用于将一个字符串形式的IPv4地址转换为32位无符号整数的网络字节序表示。
inet_aton("0.0.0.0"/*INADDR_ANY*/, &myaddr.sin_addr);
//3.为套接字文件绑定地址
if(-1 == bind(udp_socket, (struct sockaddr *)&myaddr, sizeof(myaddr))) {
perror("bind()");
goto ERROR1;
}
//加入多播组
inet_aton(GROUP_IP, &imr.imr_multiaddr);
inet_aton("0.0.0.0", &imr.imr_address);
//虚拟网卡的索引值,索引名转换为值if_nametoindex(3)
imr.imr_ifindex = if_nametoindex("ens33");
if(-1 == setsockopt(udp_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr))) {
perror("setsockopt()");
goto ERROR1;
}
//接收消息
buf = malloc(MAX_MSG);
//if error
while(1) {
memset(buf, '\0', MAX_MSG);
cnt = recvfrom(udp_socket, buf, MAX_MSG, 0, NULL, NULL);
if(-1 == cnt) {
perror("recvfrom()");
goto ERROR1;
}
if(strcmp(buf, "bye") == 0)
break;
puts(buf);
}
close(udp_socket);
free(buf);
buf = NULL;
exit(0);
ERROR1:
close(udp_socket);
exit(1);
}
server.c 负责向多播组发送消息
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <stdlib.h>
#include <unistd.h>
#include "group_proto.h"
int main(void)
{
int upd_socket;
struct sockaddr_in snd_addr;
struct ip_mreqn imr;
upd_socket = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == upd_socket){
perror("socket()");
exit(1);
}
//将本地设备设置为多播
inet_aton(GROUP_IP, &imr.imr_multiaddr);
imr.imr_address.s_addr = INADDR_ANY;
imr.imr_ifindex = if_nametoindex("ens33");
if(-1 == setsockopt(upd_socket, IPPROTO_IP, IP_MULTICAST_IF, &imr, sizeof(imr))) {
perror("setsockopot()");
goto ERROR1;
}
snd_addr.sin_family = AF_INET;
snd_addr.sin_port = htons(RCV_PORT);
inet_aton(GROUP_IP, &snd_addr.sin_addr);
while(1) {
sendto(upd_socket, "hello", 5, 0, (struct sockaddr *)&snd_addr, sizeof(snd_addr));
sleep(1);
}
close(upd_socket);
exit(0);
ERROR1:
close(upd_socket);
exit(1);
}