组播例子

1.sender.cpp

#include  
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int main(int agrc, char** argv) {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		cerr << "socket created failed...!" << endl;
		return -1;
	}
	int port = atoi(argv[1]);
	struct sockaddr_in addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		close(fd);
		cerr << "bind failed on port = " << port << endl;
		return -1;
	}
	struct ip_mreqn n = {0};
	inet_pton(AF_INET, "192.168.4.10", &n.imr_multiaddr.s_addr);	// 组播地址
	inet_pton(AF_INET, "0.0.0.0", &n.imr_address.s_addr);			// 本机地址
	n.imr_ifindex = if_nametoindex("enp8s0");						//本机的通信用的网卡的物理地址,可以用ifconfig查看
  	int ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &n, sizeof(n));
	if (ret < 0) {
		close(fd);
		cerr << "set multicast socket failed...!" << endl;
		return -1;
	}
	struct sockaddr_in client = {0};
	client.sin_family = AF_INET;
	client.sin_port = htons(6666);
	inet_pton(AF_INET, "192.168.4.10", &client.sin_addr.s_addr);
	char buf[64] = "";
	int cnt = 0;
	while (true) {
		sprintf(buf, "count = %d\n", cnt++);
		int ret = sendto(fd, buf, sizeof buf, 0, (struct sockaddr*)&client, sizeof(client));
		if (-1 == ret){
			perror("sendto -1");
		}
		sleep(1);
	}
  	close(fd);

	return 0;
}

2.receiver.cpp

#include  
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main(int agrc, char** argv) {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		cerr << "socket created failed...!" << endl;
        return -1;
    }
	struct sockaddr_in addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6666);
	inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr.s_addr);
	socklen_t len = sizeof(addr);
	if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		close(fd);
        cerr << "bind failed on port = 6666" << endl;
        return -1;
	}
	struct ip_mreqn n = {0};
	inet_pton(AF_INET, "192.168.4.10", &n.imr_multiaddr.s_addr);
	inet_pton(AF_INET, "0.0.0.0", &n.imr_address.s_addr);
	n.imr_ifindex = if_nametoindex("enp8s0");
	char buf[64] = "";
	int ret =  setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &n, sizeof(n));
	while (true) {
		int ret = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
		write(STDOUT_FILENO, buf, ret);
		sleep(1);
	}
	close(fd);

	return 0;
}

3.make.sh

g++ -std=c++17 -g -o SendTest sender.cpp -pthread
g++ -std=c++17 -g -o RecvTest receiver.cpp -pthread

 

你可能感兴趣的:(C++算法系列,设计模式,Linux)