【网络编程】Linux多播简单实现

在测试多时先确定测试的接口(网卡)是否已经开启多播功能,如下:

【网络编程】Linux多播简单实现_第1张图片

图.1

其中RUNNING MULTICAST表示开启了多播功能,可用ifconfig命令开启


多播数据发送端:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("Usage:./exec [multicast_ip] [port]\n");
        exit(-1);
    }
    struct sockaddr_in servsend;
    socklen_t len = sizeof(struct sockaddr_in);
    int ret;
    
    int sendfd = socket(AF_INET, SOCK_DGRAM, 0);
    /* 目的地址为多播地址 */
    servsend.sin_addr.s_addr = inet_addr(argv[1]);
    servsend.sin_port = htons(atoi(argv[2]));
    servsend.sin_family = AF_INET;

    u_char off = 1;
/*开启外出数据包的回馈*/
    setsockopt(sendfd, IPPROTO_IP, IP_MULTICAST_LOOP, &off, sizeof(off));

    /* 选择多播外出接口 */
    char buf[256];
    struct in_addr in;
    in.s_addr = inet_addr("192.168.1.115");
    setsockopt(sendfd, IPPROTO_IP, IP_MULTICAST_IF, &in, sizeof(in));

    
    while (1)
    {
        sprintf(buf, "I am random [%d]", (int)random()%100);
        ret = sendto(sendfd, buf, strlen(buf), 0, (struct sockaddr *)&servsend, len);
        if (ret < 0)
        {
            printf("sendto error\n");
            exit(-1);
        }
        sleep(2);
    }
    return 0;
}




多播数据接受端:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		printf("Usage:./exec [multicast_ip] [port]\n");
		exit(-1);
	}
	int ret;
	struct sockaddr_in servrecv;
	int len = sizeof(servrecv);
	int recvfd = socket(AF_INET, SOCK_DGRAM, 0);
	const int on = 1;
	ret = setsockopt(recvfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	if (ret < 0)
	{
		printf("setsockopt error\n");
		exit(-1);
	}
	
	servrecv.sin_port = htons(atoi(argv[2]));
	servrecv.sin_addr.s_addr = htonl(INADDR_ANY);
	servrecv.sin_family = AF_INET;
	ret = bind(recvfd, (struct sockaddr *)&servrecv, len);

	if (ret < 0)
	{
		printf("bind error\n");
		exit(-1);
	}

	/* 加入多播组 */
	struct ip_mreq mreq;
	mreq.imr_multiaddr.s_addr = inet_addr(argv[1]);
	mreq.imr_interface.s_addr = inet_addr("192.168.1.115");
	ret = setsockopt(recvfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));

	if (ret < 0)
	{
		printf("setsockopt error(2)\n");
		exit(-1);
	}
	struct sockaddr_in in;
	while (1)
	{
		char buf[256];
		memset(buf, 0, 256);
		len = sizeof(in);
		ret = recvfrom(recvfd, buf, 256, 0, (struct sockaddr *)&in, &len);
		if (ret < 0)
		{
			printf("recvfrom error\n");
			exit(-1);
		}
		printf("%s\n", buf);
	}
	return 0;
}


你可能感兴趣的:(C/C++,网络编程)