1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <stdio.h> #include <stdlib.h> #include <winsock2.h> #include <Ws2tcpip.h>
#define BUF_SIZE 30 void ErrorHandling(char*);
int main(int argc,char *argv[]) { WSADATA wsaData; SOCKET hAcptSock, hRecvSock;
SOCKADDR_IN recvAdr; SOCKADDR_IN sendAdr; int sendAdrSize, strLen; char buf[BUF_SIZE]; int result;
fd_set read, except, readCopy, exceptCopy; struct timeval timeout; if (argc != 2) { printf("Usage: %s <port>\n",argv[0]); exit(1); }
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error!");
hAcptSock = socket(AF_INET,SOCK_STREAM,0); memset(&recvAdr,0,sizeof(recvAdr)); recvAdr.sin_family = AF_INET; recvAdr.sin_addr.s_addr = htonl(INADDR_ANY); recvAdr.sin_port = htons(atoi(argv[1]));
if (bind(hAcptSock, (SOCKADDR*)&recvAdr, sizeof(recvAdr)) == SOCKET_ERROR) ErrorHandling("bind() error");
if (listen(hAcptSock, 5) == SOCKET_ERROR) ErrorHandling("listen() error");
sendAdrSize = sizeof(sendAdr); hRecvSock = accept(hAcptSock,(SOCKADDR*)&sendAdr,&sendAdrSize); FD_ZERO(&read); FD_ZERO(&except); FD_SET(hRecvSock,&read); FD_SET(hRecvSock,&except);
while (1) { readCopy = read; exceptCopy = except;
timeout.tv_sec = 5; timeout.tv_usec = 0;
result = select(0,&readCopy,0,&exceptCopy,&timeout);
if (result > 0) { if (FD_ISSET(hRecvSock, &exceptCopy)) { strLen = recv(hRecvSock,buf,BUF_SIZE-1,MSG_OOB); buf[strLen] = 0; printf("Urgent message: %s \n",buf); }
if (FD_ISSET(hRecvSock, &readCopy)) { strLen = recv(hRecvSock,buf,BUF_SIZE-1,0); if (strLen == 0) { closesocket(hRecvSock); break; } else { buf[strLen] = 0; puts(buf); } } } }
closesocket(hAcptSock); WSACleanup(); return 0; } void ErrorHandling(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
|