客服端骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA lpWSAData;
WSAStartup(wVersionRequested, &lpWSAData);
SOCKADDR_IN saddr{ 0 };
saddr.sin_family = AF_INET;
saddr.sin_port = htons(55555);
saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
SOCKET sRet = socket(AF_INET, SOCK_DGRAM, 0);
char opt= 0;
setsockopt(sRet, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
char buffer[0x1000]{ 0 };
while (true)
{
scanf_s("%s", buffer, sizeof(buffer));
sendto(sRet, buffer, sizeof(buffer), 0, (PSOCKADDR)&saddr, sizeof(saddr));
}
closesocket(sRet);
WSACleanup();
system("pause");
return 0;
}
服务端骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
//IP协议头 20字节
typedef struct _IP_HEADER
{
//版本信息(前四位)/头长度(后四位)
struct cVersionAndHeaderLen
{
UCHAR Version : 4;
UCHAR HeaderLen : 4;
}cVersionAndHeaderLen;
//服务类型
char cTypeOfService;
//数据包长度
short sTotalLenOfPacket;
//数据报ID
short sPacketID;
//分片信息
short sSliceinfp;
//存活时间
char cTTL;
//协议类型
char cTypeOfProtolol;
//校验和
short sCheckSum;
//源IP
unsigned int uiSourIP;
//目的IP
unsigned int uiDestIP;
}IP_HEADER, *PIP_HEADER;
//UDP协议头 8字节
typedef struct _UDP_HEADER
{
//源端口号
unsigned short usSourPort;
//目的端口号
unsigned short usDestPort;
//数据包长度
unsigned short usLength;
//校验和
unsigned short usCheckSum;
}UDP_HEADER, *PUDP_HEADER;
int main()
{
WORD wVersionRequested = MAKEWORD(2,2);
WSADATA lpWSAData;
WSAStartup(wVersionRequested, &lpWSAData);
SOCKADDR_IN saddr{ 0 };
saddr.sin_family = AF_INET;
saddr.sin_port = htons(55555);
saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
SOCKET sRet = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
char opt = 0;
setsockopt(sRet, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bind(sRet, (PSOCKADDR)&saddr, sizeof(saddr));
char buffer[0x5000]{ 0 };
sockaddr from{ 0 };
int len = sizeof(from);
IP_HEADER ih{ 0 };
UDP_HEADER uh{ 0 };
char cTemp = 0;
while (true)
{
recvfrom(sRet, buffer, sizeof(buffer), 0, &from, &len);
memcpy(&ih, buffer, 1);
if (ih.cVersionAndHeaderLen.HeaderLen < 5)//有可能小于标准20字节
{
cTemp = 5 - ih.cVersionAndHeaderLen.HeaderLen + ih.cVersionAndHeaderLen.HeaderLen;
}
memcpy(&ih, buffer, (cTemp * 4));
memcpy(&uh, buffer + (cTemp * 4), 8);
in_addr ias, iad;
ias.S_un.S_addr = ih.uiSourIP;
iad.S_un.S_addr = ih.uiDestIP;
printf("源IP:%s\t端口:%d\n", inet_ntoa(ias), ntohs(uh.usSourPort));
printf("目IP:%s\t端口:%d\n", inet_ntoa(iad), ntohs(uh.usDestPort));
printf("数据:%s\n\n", buffer + (cTemp * 4) + 8);
}
closesocket(sRet);
WSACleanup();
system("pause");
return 0;
}