网络编程:(四)组播和广播实现

广播:

#include <stdio.h>
#include <sys/types.h>			/* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
	//1.创建套接字
	int sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd == -1)
	{
		perror("socket error:");
		return -1;
	}

	//2.设置服务器的地址
	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(10086);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//自动识别本机ip

	//3.设置选项参数 (设置端口号重用)
	int val = 1;
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));

	//4.把套接字和网络地址进行绑定
	int re = bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
	if(re == -1)
	{
		perror("bind error:");
		return -1;
	}

	struct sockaddr_in addr;
	int len = sizeof(addr);
	while(1)
	{
		//接收数据
		char recvbuf[128];
		recvfrom(sockfd,recvbuf,128,0,(struct sockaddr*)&addr,&len);
		printf("ip = %s:%s\n",inet_ntoa(addr.sin_addr),recvbuf);

		
	}

	close(sockfd);
}

组播:

#include <stdio.h>
#include <sys/types.h>			/* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
	//1. 创建套接字
	int sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd == -1)
	{
		perror("socket error:");
		return -1;
	}

	//2.把本机ip加入到多播组
	struct ip_mreq mreq;
	mreq.imr_multiaddr.s_addr = inet_addr("224.1.2.3");
	//mreq.imr_interface.s_addr = inet_addr("192.168.3.13");
	mreq.imr_interface.s_addr = htonl(INADDR_ANY);
	
	//加入多播组
	setsockopt(sockfd,IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq, sizeof(mreq));	

	//3.绑定 组ip
	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(10086);
	server_addr.sin_addr.s_addr = inet_addr("224.1.2.3");// 绑定组 ip 

	//4.设置选项参数 (设置端口号重用)
	int val = 1;
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));
	
	int re = bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
	if(re == -1)
	{
		perror("bind error:");
		return -1;
	}
	printf("start:\n");
	struct sockaddr_in addr;
	int len = sizeof(addr);
	while(1)
	{
		char recvbuf[128] = {0};
		recvfrom(sockfd,recvbuf,128,0,(struct sockaddr*)&addr,&len);
		printf("ip = %s:%s\n",inet_ntoa(addr.sin_addr),recvbuf);
	}

	close(sockfd);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值