欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UDP 广播

程序员文章站 2022-06-29 18:25:23
...

代码1:

int set = 1;
	//接收数据
	if((sockListen = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
		printf("socket fail\n");
		return ;
	}
	setsockopt(sockListen, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(int));
	memset(&recvAddr, 0, sizeof(struct sockaddr_in));
	recvAddr.sin_family = AF_INET;
	recvAddr.sin_port = htons(DRIVER_PORT_NUM);
	recvAddr.sin_addr.s_addr = INADDR_ANY;
	// 必须绑定,否则无法监听
	if(bind(sockListen, (struct sockaddr *)&recvAddr, sizeof(struct sockaddr)) == -1){
		printf("bind fail\n");
		return ;
	}
    recvbytes = recvfrom(sockListen, recvbuf, 1024, 0,
						(struct sockaddr *)&recvAddr, &addrLen)) != -1

代码2:

	int brdcFd;
	int optval = 1;//这个值一定要设置,否则可能导致sendto()失败
	struct sockaddr_in theirAddr;
	int sendBytes;


	if((brdcFd = socket(PF_INET, SOCK_DGRAM, 0)) == -1){
		printf("socket fail\n");
		return ;
	}
	setsockopt(brdcFd, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &optval, sizeof(int));
	memset(&theirAddr, 0, sizeof(struct sockaddr_in));
	theirAddr.sin_family = AF_INET;
	theirAddr.sin_addr.s_addr = inet_addr("255.255.255.255");
	theirAddr.sin_port = htons(MODEL_PORT_NUM);
	if((sendBytes = sendto(brdcFd, buff2, len, 0,
					(struct sockaddr *)&theirAddr, sizeof(struct sockaddr))) == -1){
		printf("sendto model fail, errno=%d\n", errno);
		return ;
	}
	printf("send meg success...\n");