#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32")
#define LOCALPORT 2000
#define BUFSIZE 512
void errDisplay(const char* msg) {
LPVOID IpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&IpMsgBuf, 0, NULL);
printf("[%s] %s\n", msg, (char)IpMsgBuf);
LocalFree(IpMsgBuf);
}
int main(int argc, char argv[]) {
int iResult;
WSADATA wasData;
if (WSAStartup(MAKEWORD(2, 2), &wasData) != 0) {
printf("WSAStartup(): 윈속 초기화 오류\n");
return 1;
}
SOCKET dataSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (dataSocket == INVALID_SOCKET) {
errDisplay("socket()");
WSACleanup();
return 1;
}
SOCKADDR_IN localAddr;
ZeroMemory(&localAddr, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(LOCALPORT);
localAddr.sin_addr.s_addr = htons(INADDR_ANY);
iResult = bind(dataSocket, (SOCKADDR)&localAddr, sizeof(localAddr));
if (iResult == SOCKET_ERROR) {
errDisplay("bind");
closesocket(dataSocket);
WSACleanup();
return 1;
}
SOCKADDR_IN peerAddr;
int addrLength;
char buffer[BUFSIZE + 1];
addrLength = sizeof(peerAddr);
while (1) {
ZeroMemory(buffer, sizeof(buffer));
iResult = recvfrom(dataSocket, buffer, BUFSIZE, 0, (SOCKADDR)&peerAddr, &addrLength);
if (iResult == SOCKET_ERROR) {
errDisplay("recvfrom()");
break;
}
buffer[iResult] = '\n';
printf("[UDP from %s port %d] %s", inet_ntoa(peerAddr.sin_addr), ntohs(peerAddr.sin_port), buffer);
}
closesocket(dataSocket);
WSACleanup();
return 0;
}
수신