windows udp

udp的一对一通信

1.导入版本
2.确定版本信息
3.创建socket
4.初始化协议地址簇
5.绑定
6.通讯
7.结束

server端


#include 
#include
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
int main()
{
  //确定版本信息
	WSADATA wsadata;
	WSAStartup(MAKEWORD(2, 2), &wsadata);
	//3。创建socket
	SOCKET serversocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	//4.初始化地址协议簇
	SOCKADDR_IN serveraddr = {};
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(9001);
	serveraddr.sin_addr.S_un.S_addr = inet_addr("192.168.3.12");

	//5.绑定
	if (bind(serversocket, (sockaddr*)&serveraddr, sizeof(serveraddr)) > 0)
	{
		printf("绑定失败");
		return -1;
	}
	printf("绑定成功");

	//6.通讯
	char buff[128] = {};
	SOCKADDR_IN clientaddr = {};
	int len = sizeof(clientaddr);
	if (recvfrom(serversocket, buff, sizeof(buff) - 1, 0, (sockaddr*)&clientaddr, &len) > 0)
	{
		printf("来自ip:%s>>:%s\n", inet_ntoa(clientaddr.sin_addr), buff);


	}
	char tempbuff[128] = {};
	scanf_s("%s", tempbuff, 127);
	if (sendto(serversocket, tempbuff, strlen(tempbuff), 0, (sockaddr*)&clientaddr, sizeof(clientaddr) )> 0)
	{
	printf("发送成功");
	
	}
	getchar();
	getchar();
	//7.结束
	closesocket(serversocket);
	WSACleanup();
	return 0;
}


client端

// client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//


#include
#include
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
//1.导入库
//2.确定版本信息
//3.创建socket
//4.初始化协议簇
//5.通讯
//6.结束
int main()
{
   //确定版本信息
	WSADATA wsadata;
	WSAStartup(MAKEWORD(2, 2), &wsadata);
	//3.创建socket
	SOCKET clientsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	//4.初始化协议簇
	SOCKADDR_IN serveraddr = {};
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(9001);
	serveraddr.sin_addr.S_un.S_addr = inet_addr("192.168.3.12");

	//5.通讯
	char buff[128];
	scanf_s("%s", buff, 127);
	if (sendto(clientsocket, buff, strlen(buff), 0, (sockaddr*)&serveraddr, sizeof(serveraddr)) > 0)
	{
		printf("发送成功");

	}
	char tempbuff[128] = {};
	int len = sizeof(serveraddr);
	//第1个参数表示socket套接字
	//第5,6个参数表示从哪个客户端传信息过来,可给null,表示不需要知道哪个客户端传的消息,给值用来保存客户端的ip
	if (recvfrom(clientsocket, tempbuff, sizeof(tempbuff) - 1, 0, (sockaddr*)&serveraddr,&len ) > 0)
		printf("来自ip: %s >>: %s\n", inet_ntoa(serveraddr.sin_addr), tempbuff);
	getchar();
	getchar();

	//6、结束
	closesocket(clientsocket);
	WSACleanup();
	return 0;
}

你可能感兴趣的:(windows程序设计)