#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #pragma comment(lib,"ws2_32.lib")//增加几个相关lib库
#define DEFAULT_PORT 5150 #define DEFAULT_BUFFER 4096
int main(int argc,char **argv) { WSADATA wsd; SOCKET sListen; int iAddrSize, ret; struct sockaddr_in local; char szBuff[DEFAULT_BUFFER];
if(WSAStartup(MAKEWORD(2,2), &wsd)!=0) { printf("Failed to load Winsock!\n"); return 1; } sListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if(sListen == SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); }
local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_family = AF_INET; local.sin_port = htons(5000);
if(bind(sListen, (struct sockaddr *)&local, sizeof(local))==SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); return 1; }
while(1) { iAddrSize = sizeof(local); ret = recvfrom(sListen, szBuff, DEFAULT_BUFFER, 0, (struct sockaddr *)&local, &iAddrSize);
if(ret==0) break; else if(ret == SOCKET_ERROR) { printf("%d\n", WSAGetLastError()); break; }else{ szBuff[ret]='\0'; printf("RECV:%s", szBuff); } } closesocket(sListen); WSACleanup(); return 0;
}
|