服务端:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;
int ret = 0;
if ((ret = WSAStartup(MAKEWORD(2,2),&wsaData)) != 0)
{
return -1;
}
SOCKET InSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN Addr;
Addr.sin_addr.S_un.S_addr = INADDR_ANY;
Addr.sin_family = AF_INET;
Addr.sin_port = htons(12345);
bind(InSocket, (SOCKADDR *)&Addr, sizeof(SOCKADDR));
SOCKADDR_IN AddrClient;
int ClientAddrLen = sizeof(SOCKADDR_IN);
while (1)
{
char RecvBuff[1024] = { 0 };
recvfrom(InSocket, RecvBuff, 1024, 0, (SOCKADDR *)&AddrClient, &ClientAddrLen);
printf("端口是%d ", ntohs(AddrClient.sin_port));
printf("IP是%s ", inet_ntoa(AddrClient.sin_addr));
printf("数据是%s\n", RecvBuff);
memset(RecvBuff, 0, 1024);
sprintf_s(RecvBuff, 1024, "你好,客户端!我是服务器");
sendto(InSocket, RecvBuff, strlen(RecvBuff), 0, (SOCKADDR*)&AddrClient, sizeof(SOCKADDR));
}
closesocket(InSocket);
WSACleanup();
getchar();
return 0;
}
客户端
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;
int ret = 0;
if ((ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
return -1;
}
SOCKET Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SOCKADDR_IN Addr;
Addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
Addr.sin_family = AF_INET;
Addr.sin_port = htons(54321);
while (1)
{
sendto(Socket, "你好,服务器!我是客户端", strlen("你好,服务器!我是客户端"), 0, (SOCKADDR*)&Addr, sizeof(SOCKADDR));
int len = sizeof(SOCKADDR);
char buffer[1024] = { 0 };
recvfrom(Socket, buffer, 1024, 0, (SOCKADDR*)&Addr, &len);
printf("目标端口是%d ", ntohs(Addr.sin_port));
printf("目标IP是%s ", inet_ntoa(Addr.sin_addr));
printf("数据:%s\n",buffer);
}
closesocket(Socket);
WSACleanup();
getchar();
return 0;
}
|