#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"WS2_32.lib")
int main(void)
{
WSADATA wsd; // 初始化Socket的变量
SOCKET s; // 用于通信的Socket句柄
SOCKADDR_IN sRecvAddr, sSendAddr; // 分别为接收地址和发送地址
USHORT uPort = 14555; // 通信端口
CHAR szBuf[1024] = { 0 }; // 通信数据缓冲区
int nBufLen = 1024, nResult = 0, nSenderAddrSize = sizeof(sSendAddr);
// 初始化Socket2.2版本
nResult = WSAStartup(MAKEWORD(2, 2), &wsd);
if (nResult != NO_ERROR)
{
printf("WSAStartup failed:%d\n", WSAGetLastError());
return 1;
}
// 创建一个Socket,SOCK_DGRAM表示UDP类型
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("socket failed:%d\n", WSAGetLastError());
return 1;
}
// 填充Socket接口
sRecvAddr.sin_family = AF_INET; // 地址协议,AF_INET支持TCP和UDP
sRecvAddr.sin_port = htons(uPort); // 通信端口,htons转为网络字节顺序
sRecvAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); // 接收任意地址数据
// 绑定Socket至本机
nResult = bind(s, (SOCKADDR *)&sRecvAddr, sizeof(sRecvAddr));
if (nResult != 0)
{
printf("bind failed:%d\n", WSAGetLastError());
return 1;
}
printf("Waiting recv data...\n");
while (1)
{
// 阻塞式接收数据
nResult = recvfrom(s, szBuf, nBufLen, 0, (SOCKADDR *)&sSendAddr, &nSenderAddrSize);
if (nResult == SOCKET_ERROR)
{
printf("recvfrom failed:%d\n", WSAGetLastError());
}
else
{
//printf("SenderIP :%s\n", inet_ntoa(sSendAddr.sin_addr));
printf("SenderData:%s\n", szBuf);
}
}
// 关闭Socket连接
nResult = closesocket(s);
if (nResult == SOCKET_ERROR)
{
printf("closesocket failed:%d\n", WSAGetLastError());
return 1;
}
// 清理Socket
WSACleanup();
system("pause");
return 0;
}
|