socket 广播

socket 广播方式 分为两种
1.受限广播地址 即255.255.255.255
2.直接广播地址 如 192.168.100.255

使用受限广播时,UPD 方式需要绑定具体网卡才可以发送广播通信

	SOCKET  sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if ((sockfd) < 0)
	{
		return -1;
	}
	char broadcast = 1;
	int id = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char*)&broadcast, sizeof(broadcast));
	if (id < 0)
	{
		closesocket(sockfd);
		return -1;
	}

	struct sockaddr_in hostAddr = { 0 };
	hostAddr.sin_family = AF_INET;
	hostAddr.sin_addr.s_addr = inet_addr("192.168.100.175");
	hostAddr.sin_port = htons(31456);
	bind(sockfd, (struct sockaddr *)&hostAddr, sizeof(hostAddr));

使用直接广播地址时 则不需要绑定网卡地址

		struct sockaddr_in targetaddr = { 0 };
		targetaddr.sin_family = AF_INET;
		targetaddr.sin_addr.s_addr = inet_addr("192.168.100.255");
		//targetaddr.sin_addr.s_addr = INADDR_BROADCAST;
		targetaddr.sin_port = htons(21845);

		int yy = sendto(sockfd, (char*)cmd, 6, 0, (struct sockaddr *)&targetaddr, sizeof(targetaddr));

值得说明的是,局域网中 PC1 地址192.168.100.100 ,PC2地址192.168.1.100
则pc1 无法ping 通pc2,此时无法使用 直接广播发现pc2,但是可以使用受限广播发现PC2.

你可能感兴趣的:(C++,socket,c++)