c++--UDP发送接收

UDP发送接收

头文件

#include    

#pragma comment(lib,"Ws2_32.lib")//连接Sockets相关库  

初始化Windows SOCKET

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) //初始化  
{
	printf("Winsock无法初始化!\n");
	WSACleanup();
	return;
}

客户端初始化

SOCKET uSocket_client;
uSocket_client = socket(AF_INET, SOCK_DGRAM, 0);
if (uSocket_client == INVALID_SOCKET)
{
	cout << "create socket failed" << endl;
	exit(EXIT_FAILURE);
}

struct sockaddr_in server;
int server_len = sizeof(server);
server.sin_family = AF_INET;
server.sin_port = htons(PORT); ///server的监听端口
server.sin_addr.s_addr = inet_addr("192.168.100.97"); ///serve的ip

客户端发送

int len=10
char* send_char = new char[len];
int send_len = sendto(uSocket_client, send_char, len, 0, (s

你可能感兴趣的:(#,c++编程)