-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasync_echo_server_tcp.c
862 lines (862 loc) · 25.1 KB
/
async_echo_server_tcp.c
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
#include "winsock.h"
#include "winsockx.h"
#include "WSA_Xtra.h"
#include "resource.h"
#include<windows.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
#include<dos.h>
#include<direct.h>
#include<windowsx.h>
#define STRICT
/*global data*/
char szAppName[]="as_echo";
SOCKET hLstnSock=INVALID_SOCKET; /*listening socket*/
SOCKADDR_IN atLclName; /*local address and port number*/
char szHost_name[MAXHOST_NAME]={0}; /*local host name*/
int iActiveConns; /*number of active connections*/
long lByteCount; /*total bytes read*/
int iTotalConns; /*Connections closed so far*/
typedef struct stConnData
{
SOCKET hSock; /*connection socket*/
SOCKADDR_IN stRmtName; /*remote host address and port*/
LONG lStartTime; /*time of connect*/
BOOL bReadPending; /*deferred read flag*/
int iBytesRcvd; /*data currently buffered*/
int iBytesSent; /*data sent from buffer*/
long lByteCount; /*total bytes received*/
char achIOBuf[INPUT_SIZE]; /*network I/O data buffer*/
struct stConnData FAR*lpstNext; /*pointer to next record*/
}
CONNDATA, *PCONNDATA, FAR *LPCONNDATA;
LPCONNDATA lpstConnHead=0; /*head of the list*/
char szLogFile[]="as_echo.log"; /*connection log file*/
HFILE hLogFile=HFILE_ERROR;
BOOL bReAsync=TRUE;
/* Function Prototypes */
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int);
BOOL CALLBACK Dlg_Main(HWND, UINT, UINT, LPARAM);
BOOL CALLBACK Dlg_About(HWND, UINT, UINT, LPARAM);
BOOL InitLstnSock(int, PSOCKADDR_IN, HWND, u_int);
SOCKET AcceptConn(SOCKET, PSOCKADDR_IN);
long SendData(SOCKET, LPSTR, int);
int RecvData(SOCKET, LPSTR, int);
void DoStats(long, long, LPCONNDATA);
LPCONNDATA NewConn(SOCKET, PSOCKADDR_IN);
LPCONNDATA FindConn(SOCKET);
void RemoveConn(LPCONNDATA);
/*Function: WinMain()
Initialize and start message loop */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
int nRet;
lpszCmdLine=lpszCmdLine; /* avoid warning */
hPrevInstance=hPrevInstance;
nCmdShow=nCmdShow;
hInst=hInstance; /* save instance handle */
/* Initialize WinSock DLL */
nRet=WSAStartup(WSA_VERSION, &stWSAData);
/* WSAStartup() returns error value if failed (0 on success)*/
if(nRet!=0)
{
WSAperror(nRet, "WSAStartup()");
}
else
{
DialogBox(hInst, MAKEINTRESOURCE(AS_ECHO),NULL,Dlg_Main);
/*Release WinSock DLL*/
nRet=WSACleanup();
if(nRet==SOCKET_ERROR)
WSAperror(WSAGetLastError(),"WSACleanup()");
}
return(0);
} /*end of WinMain()*/
/* Function: Dlg_Main()
Precess Windows Message */
BOOL CALLBACK Dlg_Main(HWND hDlg, UINT msg, UINT wParam, LPARAM lParam)
{
LPCONNDATA lpstConn; /*work pointer*/
WORD WSAEvent, WSAErr;
SOCKADDR_IN stRmtName;
SOCKET hSock;
struct hostent *lpHost;
BOOL bRet=FALSE;
int nRet, cbRcvd, cbSent;
switch(msg)
{
case WSA_ASYNC:
/*Async notification message handlers*/
hSock=(SOCKET)wParam; /*socket*/
WSAEvent=WSAGETSELECTEVENT(lParam); /*extract event*/
WSAErr=WSAGETSELECTEVENT(lParam); /*extract error*/
lpstConn=FindConn(hSock);
/*Close connection on error (don't show error) */
if(WSAErr && (hSock!=hInstSock))
{
PostMessage(hWinMain, WSA_ASYNC, (WPARAM)hSock, WSAMAKESELECTREPLY(FD_CLOSE,0));
break;
}
switch(WSAEvent)
{
case FD_READ:
if(lpstConn)
{
/*read data from socket and write it back*/
cbRcvd=lpstConn->iBytesRcvd;
if((INPUT_SIZE - cbRcvd) > 0)
{
lpstConn->bReadPending=FALSE;
nRet=RecvData(hSock, (LPSTR)&(lpstConn->achIOBuf[cbRcvd]), INPUT_SIZE-cbRcvd);
lpstConn->iBytesRcvd+=nRet;
lpstConn->lByteCount+=nRet;
lByteCount+=nRet;
_ltoa(lByteCount, achTempBuf, 10);
SetDlgItemText(hWinMain, IDC_BYTE_TOTAL, achTempBuf);
}
else
{
/* no fucking buffer now, so defer the net read */
lpstConn->bReadPending=TRUE;
}
}
/*fall through to write data back to client*/
/*In response to FD_READ notifications, we call our own RecvData() function, evaluate the data received and update on-screen statistics*/
case FD_WRITE:
if(lpstConn && lpstConn->iBytesRcvd)
{
cbSent=lpstConn->iBytesSent;
lpstConn->iBytesSent+=SendData(hSock,(LPSTR)&(lpstConn->achIOBuf[cbSent]),lpstConn->iBytesRcvd - cbSent);
/*If everything sent which is received, then reset the counters*/
if(lpstConn->iBytesSent==lpstConn->iBytesRcvd)
{
lpstConn->iBytesSent=0;
lpstConn->iBytesRcvd=0;
}
/* if there is annoying read pending, then do it */
if(lpstConn->bReadPending)
{
PostMessage(hWinMain, WSA_ASYNC, (WPARAM)hSock, WSAMAKESELECTREPLY(FD_READ,0));
}
}
break;
/*We use FD_WRITE only after a previous send() failed with WSAEWOULDBLOCK */
case FD_ACCEPT:
/*Accept the incoming the data connection request*/
hSock=AcceptConn(hLstnSock, &stRmtName);
if(hSock!=INVALID_SOCKET)
{
/*get a new socket structure*/
lpstConn=NewConn(hSock, &stRmtName);
if(!lpstConn)
{
/*Sample libraries added: --- available in winsockx.lib and also, coded at bottom of this program ---
1. CenterWnd() - Moves window to center of parent window
2. CloseConn() - standard TCP close/shutdown
3. CreateLclFile() - create a file on local system
4. Dlg_About() - displays contents
5. GetAddr() - returns address value for host name or address string
6. GetBuf() - Gets the largest possible send or receive buffer upto a limit
7. GetHostID() - Gets local IP address
8. GetLclDir() - Gets the file directory
9. GetPort() - Gets Port number
10. WSAErrStr() - Copies short error description for WinSock into a buffer
11. WSAperror() - Displays Winsock error value
*/
CloseConn(hSock, (LPSTR)0, INPUT_SIZE, hWinMain);
}
else
{
iActiveConns++;
SetDlgItemInt(hWinMain, IDC_CONN_ACTIVE, iActiveConns, FALSE);
}
}
break;
case FD_CLOSE: /*data connection closed*/
if(hSock!=hLstnSock)
{
/*read any remaining data and close connection*/
CloseConn(hSock, (LPSTR)0, INPUT_SIZE, hWinMain);
if(lpstConn)
{
DoStats(lpstConn->lByteCount, lpstConn->lStartTime, lpstConn);
RemoveConn(lpstConn);
iTotalConns++;
SetDlgItemInt(hWinMain, IDC_CONN_TOTAL, iTotalConns, FALSE);
iActiveConns--;
SetDlgItemInt(hWinMain, IDC_CONN_ACTIVE, iActiveConns, FALSE);
}
}
break;
default:
break;
}
/*end of switch(WSAEvent)*/
break;
case WM_COMMAND:
switch(wParam)
{
case IDC_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUT), hDlg, Dlg_About);
break;
case WM_DESTROY:
case IDC_EXIT:
/*close listening socket*/
if(hLstnSock!=INVALID_SOCKET)
closesocket(hLstnSock);
/*close all active connections*/
for(lpstConn=lpstConnHead;lpstConn;lpstConn=lpstConn->lpstNext)
{
CloseConn(lpstConn->hSock,(LPSTR)0,INPUT_SIZE,hWinMain);
RemoveConn(lpstConn);
}
/*write final stats and close log file */
if(hLogFile!=HFILE_ERROR)
{
wsprintf(achTempBuf, "Final Total: Bytes Received: %lu, Connections: %d \n", lByteCount, iTotalConns);
_lwrite(hLogFile, achTempBuf, strlen(achTempBuf));
_lclose(hLogFile);
}
EndDialog(hDlg, msg);
bRet=TRUE;
break;
default:
break;
}
/*end of WM_COMMAND */
break;
case WM_INITDIALOG:
hWinMain=hDlg; /*save main window handle */
/*get socket listener*/
hLstnSock=InitLstnSock(IPPORT_ECHO, &stLclName, hWinName, WSA_ASYNC);
/*get local info for display*/
stLclName.sin_addr.s_addr=GetHostID();
gethostname(szHost name, MAXHOST_NAME);
wsprintf(achTempBuf, "Local host: %s (%s)", inet_ntoa(stLclName.sin_addr), szHost_name[0] ? (LPSTR)szHost_name : (LPSTR)"<unknown>");
SetDlgItemText(hWinMain,IDC_LOCAL_HOST,achTempBuf);
/*assign an icon to dialog box*/
#ifndef WIN32
SetClassWord(hDlg,GCW_HICON,(WORD)LoadIcon(hInst,MAKEINTRESOURCE(AS_ECHO)));
#else
SetClassLong(hDlg,GCL_HICON,(LONG)LoadIcon((HINSTANCE) GetWindowLong(hDlg, GWL_HINSTANCE), __TEXT("AS_ECHO")));
#endif
/*open log file "if" logging is enabled */
hLogFile= _lcreat(szLogFile, 0);
if(hLogFile==HFILE_ERROR)
{
MessageBox(hWinMain, "unable to open log file", "file error", MB_OK | MB_ICONASTERISK);
}
/*center dialog box*/
CenterWnd(hDlg,NULL,TRUE);
break;
default:
break;
}
/*end switch(msg) */
return(bRet);
}
/*end of Dlg_Main()*/
/*---Function: InitLstnSock()
Get a stream socket and start listening for incoming connection requests */
BOOL InitLstnSock(int iLstnPort, PSOCKADDR_IN pstSockName, HWND hwnd, u_int nAsyncMsg)
{
int nRet;
SOCKET hLstnSock;
int nLen=SOCKADDR_LEN;
/*Get a TCP socket to use for data connection ~ listen*/
hLstnSock=socket(AF_INET, SOCK_STREAM, 0);
if(hLstnSock==INVALID_SOCKET)
{
WSAperror(WSAGetLastError(), "socket()");
} else
{
/*request async notifications for most events*/
nRet=WSAAsyncSelect(hLstnSock, hWnd, nAsyncMsg,(FD_ACCEPT | FD_READ | FD_WRITE | FD_CLOSE));
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"WSAAsyncSelect()");
}
else
{
/*name the local socket with bind()*/
pstSockName->sin_family=PF_INET;
pstSockName->sin_port=htons(iLstnPort);
nRet=bind(hLstnSock,(LPSOCKADDR)pstSockName,SOCKADDR_LEN);
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(), "listen()");
}
}
}
/* if we get an error, OMG! Then, we gotta problem. Clean the shit up! */
if(nRet==SOCKET_ERROR)
{
closesocket(hLstnSock);
hLstnSock=INVALID_SOCKET;
}
}
return(hInstSock);
} /*end of InitLstnSock() */
/*--- Function: AcceptConn()
In response to FD_ACCEPT, call accept() inorder to respond to connection request & establish connection*/
SOCKET AcceptConn(SOCKET hLstnSock, PSOCKADDR_IN pstName)
{
SOCKET hNewSock;
int nRet, nLen = SOCKADDR_LEN;
hNewSock=accept(hLstnSock,(LPSOCKADDR)pstName,(LPINT)&nLen);
if(hNewSock==SOCKET_ERROR)
{
int WSAErr = WSAGetLastError();
if(WSAErr!=WSAEWOULDBLOCK)
WSAperror(WSAErr,"accept");
}
else if(bReAsync)
{
nRet=WSAAsyncSelect(hNewSock,hWinMain,WSA_ASYNC,(FD_READ | FD_WRITE | FD_CLOSE));
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"WSAAsyncSelect()");
}
/*getting extra buffer space*/
GetBuf(hNewSock, INPUT_SIZE, SO_RCVBUF);
GetBuf(hNewSock, INPUT_SIZE, SO_SNDBUF);
}
return(hNewSock);
} /*end AcceptConn() */
/*--- Function: SendData()
Send data from buffer provided
*/
long SendData(SOCKET hSock, LPSTR lpOutBuf, int cbTotalToSend)
{
int cbTotalSent=0;
int cbLeftToSend = cbTotalToSend;
int nRet, WSAErr;
/*Sending data*/
while(cbLeftToSend > 0)
{
/*Send data to client*/
nRet=send(hSock,lpOutBuf+cbTotalSent,cbLeftToSend < MTU_SIZE ? cbLeftToSend : MTU_SIZE, 0);
if(nRet==SOCKET_ERROR)
{
WSAErr=WSAGetLastError();
/*display errors*/
if(WSAErr!=WSAEWOULDBLOCK)
{
WSAperror(WSAErr, (LPSTR)"send()");
}
break;
}
else
{
/*update byte counter and display*/
cbTotalSent+=nRet;
}
/*calculate the remaining ones =P */
cbLeftToSend=cbTotalToSend - cbTotalSent;
}
return(cbTotalSent);
} /*end of SendData() */
/*--- Function:- RecvData()
Receive data into buffer provided */
int RecvData(SOCKET hSock, LPSTR lpInBuf, int cbTotalToRecv)
{
int cbTotalRcvd=0;
int cbLeftToRecv=cbTotalToRecv;
int nRet=0, WSAErr;
/*read buffer from client*/
while(cbLeftToRecv > 0)
{
nRet=recv(hSock,lpInBuf+cbTotalRcvd,cbLeftRecv,0);
if(nRet==SOCKET_ERROR)
{
WSAErr=WSAGetLastError();
/*display errors*/
if(WSAErr!=WSAEWOULDBLOCK)
WSAperror(WSAErr,(LPSTR)"recv()");
/*exit recv() loop on any error*/
break;
}
else if(nRet==0)
{
/*other side closed socket*/
/*quit if server closed connection*/
break;
}
else
{
/*update byte counter*/
cbTotalRcvd+=nRet;
}
cbLeftToRecv=cbTotalToRecv - cbTotalRcvd;
}
return(cbTotalRcvd);
} /*end RecvData() */
/*---Function: DoStats()
Display data transfer rate */
void DoStats(long lByteCount, long lStartTime, LPCONNDATA lpstConn)
{
LONG dByteRate;
LONG lMSecs;
/*calculate data transfer rate and display*/
lMSecs=(LONG) GetTickCount() - lStartTime;
if(lMSecs <= 55)
lMSecs=27;
if(lByteCount>0L)
{
if(lpstConn)
{
wsprintf(achTempBuf,"<<< socket: %d disconnected from %s \n", lpstConn->hSock, inet_ntoa(lpstConn->stRmtName.sin_addr));
_lwrite(hLogFile, achTempBuf, strlen(achTempBuf));
}
dByteRate=(lByteCount/lMSecs); /*Data rate*/
wsprintf(achTempBuf, "%ld bytes in %ld.%ld seconds (%ld.%ld Kbytes/sec)\n",lByteCount,lMSecs/1000,lMSecs%1000,(dByte*1000)/1024,(dByteRate*1000)%1024);
SetDlgItemText(hWinMain,IDC_DATA_RATE,achTempBuf);
if(hLogFile!=HFILE_ERROR)
_lwrite(hLogFile, achTempBuf, strlen(achTempBuf));
}
} /*end of DoStats() */
/*---Function : NewConn()
Create a new socket structure and put in list */
LPCONNDATA NewConn(SOCKET hSock, PSOCKADDR_IN pstRmtName)
{
int nAddrSize=sizeof(SOCKADDR);
LPCONNDATA lpstConnTmp, lpstConn=(LPCONNDATA)0;
HLOCAL hSockData;
/*allocate memory for new socket structure*/
hSockData=LocalAlloc(LMEM_ZEROINIT,sizeof(SOCKDATA));
if(hSockData!=0)
{
/*lock it and link it into the list*/
lpstConn=LocalLock(hSockData);
if(!lpstConnHead)
{
lpstConnHead=lpstConn;
}
else {
for(lpstConnTmp=lpstConnHead;lpstConnTmp && lpstConnTmp->lpstNext;lpstConnTmp=lpstConnTmp->lpstNext);
lpstConnTmp->lpstNext=lpstConn;
}
/*Initialize socket structure*/
lpstConn->hSock=hSock;
_fmemcpy((LPSTR)&&(lpstConn->stRmtName),(LPSTR)pstRmtName,sizeof(SOCKADDR));
lpstConn->lStartTime=GetTickCount();
/*Log the new connection*/
if(hLogFile!=HFILE_ERROR)
{
wsprintf(achTempBuf,">>> socket: %d connected from %s \n", hSock, inet_ntoa(lpstConn->stRmtName.sin_addr));
_lwrite(hLogFile,achTempBuf,strlen(achTempBuf));
}
}
else
{
MessageBox(hWinMain, "unable to allocate memory for connectivity", "LocalAlloc() Error", MB_OK | MB_ICONASTERISK);
}
return(lpstConn);
} /*end of NewConn() */
/* Function:--- FindConn()
Find socket structure for connection */
LPCONNDATA FindConn(SOCKET hSock)
{
LPCONNDATA lpstConnTmp;
for(lpstConnTmp=lpstConnHead;lpstConnTmp;lpstConnTmp=lpstConnTmp->lpstNext)
{
if(lpstConnTmp->hSock==hSock)
break;
}
return(lpstConnTmp);
} /*end of FindConn() */
/*--- Function: RemoveConn()
Free the memory for socket structure */
void RemoveConn(LPCONNDATA lpstConn)
{
LPCONNDATA lpstConnTmp;
HLOCAL hSock;
if(lpstConn==lpstConnHead)
{
lpstConnHead=lpstConn->lpstNext;
}
else
{
for(lpstConnTmp=lpstConnHead;lpstConnTmp;lpstConnTmp=lpstConnTmp->lpstNext)
{
if(lpstConnTmp->lpstNext==lpstConn)
lpstConnTmp->lpstNext=lpstConn->lpstNext;
}
}
hSock=LocalHandle(lpstConn);
LocalUnlock(hSock);
LocalFree(hSock);
} /*end of RemoveConn() */
/*Function: CenterWnd()
Center window relative to the parent window */
void CenterWnd(HWND hWnd, HWND hParentWnd, BOOL bPaint)
{
RECT rc2, rc1;
RECT FAR, *lprc;
int nWidth, nHeight, cxCenter, cyCenter;
if(!hParentWnd) /*if we've no parent, then use desktop*/
hParentWnd=GetDesktopWindow();
GetWindowRect(hParentWnd,&rc2);
lprc=(RECT FAR *)&rc2;
cXCenter=lprc->left+((lprc->right-lprc->left)/2);
cyCenter=lprc->top+((lprc->bottom-lprc->top)/2);
MoveWindow(hWnd, cXCenter-(nWidtth/2), cyCenter-(nHeight/2), nWidth, nHeight, bPaint);
return;
} /*end of CenterWnd() */
/*Function: CloseConn()
Closing TCP connection, ensuring that no data loss can occur on WInSocks that post FD_CLOSE when data is still available to read
*/
int CloseConn(SOCKET hSock, LPSTR achInBuf, int len, HWND hWnd)
{
int nRet;
char achDiscard(BUF_SIZE);
int cbBytesToDo=len, cbBytesDone=0;
if(hSock!=INVALID_SOCKET)
{
/*disable asynchronous notification if window handle is provided*/
if(hWnd)
{
nRet=WSAAsyncSelect(hSock, hWnd, 0, 0);
if(nRet==SOCKET_ERROR)
WSAperror(WSAGetLastError(),"CloseConn() WSAAsyncSelect()");
}
/*half-closing the connecting*/
nRet=shutdown(hSock,l);
/*read remaining data*/
for(nRet=1;(nRet && (nRet!=SOCKET_ERROR));)
{
if(achInBuf)
{
nRet=recv(hSock,&achInBuf[cbBytesDone],cbBytesToDo,0);
if(nRet && (nRet!=SOCKET_ERROR))
{
cbBytesToDo-=nRet;
cbBytesDone+=nRet;
}
}
else
{
/*no buffer provided, so discard any data*/
nRet=recv(hSock,achDiscard,BUF_SIZE,0);
}
}
/*closing the socket*/
closesocket(hSock);
}
return(nRet);
} /*end of CloseConn()*/
/*Function: CreateLclFile()
Try to create a file on local system and notify user if fails and then prompt for new file name*/
HFILE CreateLclFile(LPSTR szFileName)
{
HFILE hFile;
char szRmtFile(MAXFILENAME);
hFile= _lcreat (szFileName, 0); /*creating the file*/
strcpy(szRmtFile,szFileName); /*save remote file name*/
while(hFile==HFILE_ERROR)
{
wsprintf(achTempBuf,"Unable to create the file %s, Change the file name", szFileName);
MessageBox(hWinMain,achTempBuf,"File Error",MB_OK | MB_ICONASTERISK);
if(!DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hWinMain,Dlg_File))
{
/*no new file name is provided, so quit*/
break;
}
else
{
/*try creating a new file*/
hFile= _lcreat(szFileName, 0);
}
}
strcpy(szFileName,szRmtFile); /*replace remote filename*/
return hFile;
} /*end of CreateLclFile() */
/*Function: Dlg_About()
Displays and WinSock DLL info */
BOOL CALLBACK Dlg_About
{
HWND hDlg;
UINT msg;
UINT wParam;
LPARAM lParam;
{
char achDataBuf[WSADESCRIPTION_LEN+1];
lParam=lParam; /*avoid warning*/
switch(msg)
{
case WM_INITDIALOG:
wsprintf(achDataBuf,"(Compiled: %s, %s) \n",(LPSTR)__DATE__,(LPSTR)__Time__);
SetDlgItemText(hDlg, IDC_COMPILEDATE,(LPCSTR)achDataBuf);
wsprintf(achDataBuf, "Version:%d.%d",LOBYTE(stWSAData.wVersion)/*major version*/,HIBYTE(stWSAData.wVersion))/*minor version*/;
SetDlgItemText(hDlg,IDS_DLLVER,(LPCSTR)achDataBuf);
wsprintf(achDataBuf,"NewVersion:%d.%d",LOBYTE(stWSAData.wVersion)/*major version*/,HIBYTE(stWSAData.wVersion))/*minor version*/;
SetDlgItemText(hDlg,IDS_DLLHIVER,achDataBuf);
SetDlgItemText(hDlg,IDS_DESCRIP,(LPCSTR)(stWSAData.szDescription));
SetDlgItemText(hDlg,IDS_STATUS,(LPCSTR)(stWSAData.szSystemStatus));
wsprintf(achDataBuf,"MaxSockets: %u",stWSAData.iMaxSockets);
SetDlgItemText(hDlg,IDS_MAXSOCKS,(LPCSTR)achDataBuf);
wsprintf(achDataBuf,"iMaxUdp: %u",stWSAData.iMaxUdpDg);
SetDlgItemText(hDlg,IDS_MAXUDP,(LPCSTR)achDataBuf);
/*center dialog box*/
CenterWnd(hDlg,hDlgMain,TRUE);
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
EndDialog(hDlg,0);
return TRUE;
}
break;
}
return FALSE;
} /*end of Dlg_About()*/
/*Function:-- GetAddr()
Given a string, it will return an IP address. First, it tries to convert directly. if it fails, it tries to resolve as host name
*/
u_long GetAddr(LPSTR,szHost)
{
LPHOSTENT lpstHost;
u_long lAddr=INADDR_ANY;
/*check if string exists*/
if(*szHost)
{
/*check for a dotted IP address string*/
lAddr=inet_addr(szHost);
/*if not an address, then trying to resolve it as host name*/
if((lAddr==INADDR_NONE) && (_fstrcmp (szHost,"255.255.255.255")))
{
lpstHost=gethostbyname(szHost);
if(lpstHost)
{
/*success*/
lAddr= *((u_long FAR *) (lpstHost->h_addr));
}
else
{
lAddr=INADDR_ANY; /*failure*/
}
}
}
return(lAddr);
} /*end of GetAddr()*/
/*Function: GetBuf()
Getting send/receive buffer space as WinSock starts with the amount requested */
int GetBuf(SOCKET hSock, int nBigBufSize, int nOptval);
int nRet, nTrySize, nFinalSize=0;
for(nTrySize=nBigBufSize;nTrySize>MTU_SIZE;nTrySize>>=1)
{
nRet=setsockopt(hSock,SOL_SOCKET,nOptval,(char FAR*)&nTrySize,sizeof(int));
if(nRet==SOCKET_ERROR)
{
int WSAErr=WSAGetLastError();
if((WSAErr==WSAENOPROTOOPT)||(WSAErr==WSAEINVAL))
break;
}
else
{
nRet=sizeof(int);
getsockopt(hSock,SOL_SOCKET,nOptval,(char FAR*)&nFinalSize,&nRet);
break;
}
}
return(nFinalSize);
} /*end of GetBuf() */
/* Function:---- GethostID()
Getting host IP address using this algorithm:
~~ Get local host name with gethostname()
~~ Attempt to resolve local host name with gethostbyname()
If that fails, then
~~ Get UDP socket
~~ Connect UDP socket to arbitrary address and port
~~ Use getsockname() to get local address
*/
LONG GetHostID()
{
char szLclHost [MAXHOSTNAME];
LPHOSTENT lpstHostent;
SOCKADDR_IN stLclAddr;
SOCKADDR_IN stRmtAddr;
int nAddrSize=sizeof(SOCKADDR);
SOCKET hSock;
int nRet;
/*init local address to zero*/
stLclAddr.sin_addr.s_addr=INADDR_ANY;
/*get local host name*/
nRet=gethostname(szLclHost,MAXHOSTNAME);
if(nRet!=SOCKET_ERROR)
{
/*resolve host name for local address*/
lpstHostent=gethostbyname((LPSTR)szLclHost);
if(lpstHostent)
stLclAddr.sin_addr.s_addr= *((u_long FAR*) (lpstHostent->h_addr));
}
/*if not yet resolved, then try second strategy*/
if(stLclAddr.sin_addr.s_addr==INADDR_ANY)
{
/*Get UDP socket*/
hSock=socket(AF_INET,SOCK_DGRAM,0);
if(hSock!=INVALID_SOCKET)
{
/*connect to arbitrary port and address*/
stRmtAddr.sin_family=AF_INET;
stRmtAddr.sin_port=htons(IPPORT_ECHO);
stRmtAddr.sin_addr.s_addr=inet_addr("128.127.50.1");
nRet=connect(hSock,(LPSOCKADDR)&stRmtAddr,sizeof(SOCKADDR));
if(nRet!=SOCKET_ERROR)
{
/*get local address*/
getsockname(hSock,(LPSOCKADDR)&stLclAddr,(int FAR*)&nAddrSize);
}
closesocket(hSock); /*Woo hoo! Good night socket. */
}
}
return(stLclAddr.sin_addr.s_addr);
} /*End of GetHostID() */
/*--Function: GetLclDir()
Temporary file for later display */
BOOL GetLclDir(LPSTR szTempFile)
{
#ifdef WIN32
struct _finddata_t stFile; /* Microsoft's 32-bit 'Find' file structure */
#else
struct _find_t stFile; /* Microsoft's 16-bit 'Find' file structure */
#endif
HFILE hTempFile;
int nNext;
hTempFile = CreateLclFile(szTempFile);
if(hTempFile!=HFILE_ERROR)
{
#ifdef WIN32
nNext =_findfirst("*.*",&stFile);
while(!nNext)
{
wsprintf(achTempBuf,"%-12s %.24s %9ld\n",stFile.name,ctime(&(stFile.time_write)),stFile.size);
_lwrite(hTempFile,achTempBuf,strlen(achTempBuf));
nNext= _findnext(nNext, &stFile);
}
#else
nNext= _dos_findfirst("*.*",0,&stFile);
while(!nNext)
{
unsigned month,day,year,hour,second,minute;
month=(stFile.wr_date>>5) & 0XF;
day=stFile.wr_date & 0X1F;
year=((stFile.wr_date>>9) & 0X7F) + 80;
hour=(stFile.wr_time>>11) & 0X1F;
minute=(stFile.wr_time>>5) & 0X3F;
second=(stFile.wr_time & 0X1F) << 1;
wsprintf(achTempBuf,"%s\t\t%ld bytes \t%d-%d-%d \t%.2d:%.2d:%.2d\r\n",stFile.name,stFile.size,month,day,year,hour,minute,second);
_lwrite(hTempFile,achTempBuf,strlen(achTempBuf));
nNext= _dos_findnext(&stFile);
}
#endif
_lclose(hTempFile);
return(TRUE);
}
return(FALSE);
} /* end of GetLclDir() */
/*--Function: GetLclDir()
Temporary file for later display */
BOOL GetLclDir(LPSTR szTempFile)
{
#ifdef WIN32
struct _finddata_t stFile; /* Microsoft's 32-bit 'Find' file structure */
#else
struct _find_t stFile; /* Microsoft's 16-bit 'Find' file structure */
#endif
HFILE hTempFile;
int nNext;
hTempFile = CreateLclFile(szTempFile);
if(hTempFile!=HFILE_ERROR)
{
#ifdef WIN32
nNext =_findfirst("*.*",&stFile);
while(!nNext)
{
wsprintf(achTempBuf,"%-12s %.24s %9ld\n",stFile.name,ctime(&(stFile.time_write)),stFile.size);
_lwrite(hTempFile,achTempBuf,strlen(achTempBuf));
nNext= _findnext(nNext, &stFile);
}
#else
nNext= _dos_findfirst("*.*",0,&stFile);
while(!nNext)
{
unsigned month,day,year,hour,second,minute;
month=(stFile.wr_date>>5) & 0XF;
day=stFile.wr_date & 0X1F;
year=((stFile.wr_date>>9) & 0X7F) + 80;
hour=(stFile.wr_time>>11) & 0X1F;
minute=(stFile.wr_time>>5) & 0X3F;
second=(stFile.wr_time & 0X1F) << 1;
wsprintf(achTempBuf,"%s\t\t%ld bytes \t%d-%d-%d \t%.2d:%.2d:%.2d\r\n",stFile.name,stFile.size,month,day,year,hour,minute,second);
_lwrite(hTempFile,achTempBuf,strlen(achTempBuf));
nNext= _dos_findnext(&stFile);
}
#endif
_lclose(hTempFile);
return(TRUE);
}
return(FALSE);
} /* end of GetLclDir() */
/*Function: GetPort()
Returns a port number from a string. It involves converting from ASCII to integer or resolving as service name.
This function is limited since it assumes the service name that will not begin with an integer where it is possible like we say "Cat on the wall!"
*/
u_short GetPort(LPSTR szService)
{
u_short nPort=0; /*Port 0 is invalid*/
LPSERVENT lpServent;
char c;
c= *szService;
if((c>='1') && (c<='9'))
{
/*convert ASCII to integer and put in network order*/
nPort=htons((u_short)atoi (szService));
}
else
{
/*resolve service name to port number*/
lpServent=getservbyname((LPSTR)szService,(LPSTR)"tcp");
if(!lpServent)
{
WSAperror(WSAGetLastError( ),"getservbyname( )");
}
else
{
nPort=lpServent->s_port;
}
}
return(nPort);
} /*end of GetPort() */
/*Function: GetWSAErrStr()
Given a winsock error value, return error string
*/
int GetWSAErrStr(int WSAErr, LPSTR lpErrBuf)
{
int err_len=0;
HANDLE hInst;
HWND hwnd;
hwnd=GetActiveWindow();
hInst=GetWindowWord(hwnd,GWW_HINSTANCE);
if(WSAErr==0)
WSAErr=WSABASEERR; /*base resource file number*/
if(WSAErr >= WSABASEERR) /*valid error code*/
/*get error string in the table from the resource file*/
err_len=LoadString(hInst,WSAErr,lpErrBuf,ERR_SIZE/2);
return(err_len);
} /*end of GetWSAErrStr() */
/*Function: WSAperror()
Displays the input parameter string and string description that corresponds to winsock error value input parameter */
void WSAperror(int WSAErr,LPSTR szFuncName)
{
static char achErrBuf[ERR_SIZE]; /*buffer for errors*/
static char achErrMsg[ERR_SIZE/2];
WSAErrStr(WSAErr,achErrMsg);
wsprintf(achErrBuf,"%s failed,%-40c\n\n%s",szFuncName,' ',achErrMsg);
/*display error message, it doesn't matter whether it's complete or not */
MessageBox(GetActiveWindow,achErrBuf,"Error",MB_OK | MB_ICONHAND);
return;
} /*end of WSAperror() */