1. Server
/*
*端口使用一个16位的数字表示,范围0~65535, 1024一下端口保留
*低位先存:起始地址放在低位字节
*高位先存:起始地址放在高位字节
*Intel CPU:地位先存
*TCP/IP使用16位和32位整数的高位先存格式
*/
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
return -1;
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return -1;
}
SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
char recvBuf[100];
recvfrom(sockSrv, recvBuf, 100, 0,(SOCKADDR*)&addrClient, &len);
printf("%s\n", recvBuf);
closesocket(sockSrv);
WSACleanup();
return 0;
}
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData))
{
return -1;
}
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return -1;
}
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.s_addr = inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
sendto(sockClient, "hello", strlen("hello")+1, 0, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
closesocket(sockClient);
WSACleanup();
return 0;
}