UDP send 代码

这里列出了两种方法,第一种是不指定本地端口号和ip,第二种是指定本地端口号和ip。首选第二种。

方法一:

#include 
#include 

int main()
{ 
	printf("发送方:\n");
	
	SOCKET sock;
	sockaddr_in remote;//远端地址
	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;
	}

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

	while (1)
	{
		memset(buf, 0, 128);
		sprintf_s(buf, "%s", "hello");
		len = 5;

		//将buf中的内容发送到远端
		sendto(sock, buf, len, 0, (struct sockaddr*)&remote, addr_len);

		system("pause");
	}

    closesocket(sock);
	return 0;
}
方法二:

#include 
#include 

int main()
{ 
	printf("发送方:port=9000 ...\n");
	
	SOCKET sock;
	sockaddr_in local;//本地地址
	sockaddr_in remote;//远端地址
	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(9000);
	local.sin_addr.s_addr = inet_addr("127.0.0.1");

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

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

	while (1)
	{
		memset(buf, 0, 128);
		sprintf_s(buf, "%s", "hello");
		len = 5;

		//将buf中的内容发送到远端
		sendto(sock, buf, len, 0, (struct sockaddr*)&remote, sizeof(sockaddr_in));

		system("pause");
	}
    
    closesocket(sock);
	return 0;
}



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