UDP receive 代码

本代码为使用UDP协议接受信息的代码。

#include 
#include 

int main()
{
	printf("接收方:port=9001...\n");
	
	SOCKET sock;
	sockaddr_in local;//本地ip和端口
	sockaddr_in remote;//远端ip和端口,先不用管,接收到信息后自动为其赋值
	int addr_len = sizeof(sockaddr_in);
	char buf[128];
	int len = 0;

	/*创建socket*/
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
	{
		printf("create socket failed!\n");
		return -1;
	}

	/*填写local*/
	local.sin_family = AF_INET;
	local.sin_port = htons(9001);
	local.sin_addr.s_addr = htonl(INADDR_ANY);// inet_addr("127.0.0.1");

	/*绑定端口*/
	if (bind(sock, (sockaddr*)&local, addr_len) < 0)
	{
		printf("binding socket failed!\n");
		return -1;
	}

	while (1)
	{
		memset(buf, 0, 128);
		len = recvfrom(sock, buf, sizeof(buf), 0, (sockaddr*)&remote, &addr_len);
		//len = recvfrom(sock, buf, sizeof(buf), 0, NULL, NULL);这里如果不想知道对面ip和端口的话,也可以这样写
		if (len > 0)
		{
			printf("%s\n", buf);
		}
	}

	closesocket(sock);
	return 0;
}


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