-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathSocketHandle.cpp
1196 lines (1084 loc) · 34.8 KB
/
SocketHandle.cpp
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#ifdef WIN32
#include <stdlib.h>
#ifndef UNDER_CE
#include <crtdbg.h>
#endif
#include <strsafe.h>
#endif
#include "SocketHandle.h"
#ifndef BUFFER_SIZE
#define BUFFER_SIZE 64*1024
#endif
#ifndef SOCKHANDLE_TTL
#define SOCKHANDLE_TTL 5
#endif
#ifndef SOCKHANDLE_HOPS
#define SOCKHANDLE_HOPS 10
#endif
#define HOSTNAME_SIZE MAX_PATH
#define STRING_LENGTH 40
#if !defined(PLATFORM_HAS_INETFUNC)
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
int inet_pton(int af, const char *src, void *dst);
#endif
#ifdef WIN32
#ifndef UNDER_CE
#pragma comment(lib, "ws2_32.lib")
#else
#pragma comment(lib, "Ws2.lib")
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
// SockAddrIn Struct
SockAddrIn SockAddrIn::NULLAddr;
///////////////////////////////////////////////////////////////////////////////
// Constructs
SockAddrIn::SockAddrIn()
{
Clear();
}
SockAddrIn::SockAddrIn(const SockAddrIn& sin)
{
Copy( sin );
}
SockAddrIn::~SockAddrIn()
{
}
///////////////////////////////////////////////////////////////////////////////
// Clear
void SockAddrIn::Clear()
{
memset(this, 0, sizeof(sockaddr_storage));
}
///////////////////////////////////////////////////////////////////////////////
// Copy
SockAddrIn& SockAddrIn::Copy(const SockAddrIn& sin)
{
ss_family = sin.ss_family;
memcpy(this, &sin, Size());
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// IsEqual
bool SockAddrIn::IsEqual(const SockAddrIn& sin) const
{
// Is it Equal? - ignore 'sin_zero'
if ( ss_family == AF_INET ) {
return (memcmp(this, &sin, Size()-8) == 0);
}
return (memcmp(this, &sin, Size()) == 0);
}
///////////////////////////////////////////////////////////////////////////////
// CreateFrom
bool SockAddrIn::CreateFrom(LPCTSTR pszAddr, LPCTSTR pszService, int nFamily /*=AF_INET*/)
{
Clear();
CSocketHandle::GetAddressInfo(pszAddr, pszService, nFamily, *this);
return !IsNull();
}
///////////////////////////////////////////////////////////////////////////////
// CreateFrom
bool SockAddrIn::CreateFrom(ULONG lIPAddr, USHORT nPort, int nFamily /*= AF_INET*/, bool bFmtHost /*= true*/)
{
Clear();
_ASSERTE( nFamily == AF_INET ); // supports IPv4 only
SOCKADDR_IN* psin = reinterpret_cast<SOCKADDR_IN*>(this);
psin->sin_family = static_cast<short>(nFamily);
if ( bFmtHost )
{
psin->sin_addr.s_addr = htonl( lIPAddr );
psin->sin_port = htons( nPort );
}
else
{
psin->sin_addr.s_addr = lIPAddr;
psin->sin_port = nPort;
}
return !IsNull();
}
///////////////////////////////////////////////////////////////////////////////
// CSocketHandle
CSocketHandle::CSocketHandle()
: m_hSocket(INVALID_SOCKET)
{
}
CSocketHandle::~CSocketHandle()
{
Close();
}
///////////////////////////////////////////////////////////////////////////////
// IsOpen
bool CSocketHandle::IsOpen() const
{
return ( INVALID_SOCKET != m_hSocket );
}
///////////////////////////////////////////////////////////////////////////////
// GetSocket
SOCKET CSocketHandle::GetSocket() const
{
return m_hSocket;
}
///////////////////////////////////////////////////////////////////////////////
// GetSocketType
int CSocketHandle::GetSocketType() const
{
int type = -1;
if ( INVALID_SOCKET != m_hSocket ) {
socklen_t optlen = sizeof(int);
if ( getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, reinterpret_cast<char*>(&type),
&optlen) == SOCKET_ERROR)
{
SetLastError( WSAGetLastError() );
}
}
return type;
}
///////////////////////////////////////////////////////////////////////////////
// Attach
bool CSocketHandle::Attach(SOCKET sock)
{
if ( INVALID_SOCKET == m_hSocket )
{
m_hSocket = sock;
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// Detach
SOCKET CSocketHandle::Detach()
{
SOCKET sock;
#ifdef _WIN64
#pragma warning(push)
#pragma warning(disable:4311 4312)
sock = reinterpret_cast<SOCKET>(
InterlockedExchangePointer((void**)&m_hSocket, (void*)INVALID_SOCKET) );
#pragma warning(pop)
#else
sock = m_hSocket;
::InterlockedExchange(reinterpret_cast<long*>(&m_hSocket), INVALID_SOCKET);
#endif
return sock;
}
///////////////////////////////////////////////////////////////////////////////
// GetSockName
bool CSocketHandle::GetSockName(SockAddrIn& saddr_in) const
{
_ASSERTE( IsOpen() );
if (IsOpen()) {
socklen_t namelen = (socklen_t)saddr_in.Size();
if (SOCKET_ERROR != getsockname(GetSocket(), saddr_in, &namelen))
{
return true;
}
SetLastError( WSAGetLastError() );
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetPeerName
bool CSocketHandle::GetPeerName(SockAddrIn& saddr_in) const
{
_ASSERTE( IsOpen() );
if (IsOpen()) {
socklen_t namelen = (socklen_t)saddr_in.Size();
if (SOCKET_ERROR != getpeername(GetSocket(), saddr_in, &namelen))
{
return true;
}
SetLastError( WSAGetLastError() );
}
return false;
}
// Close
void CSocketHandle::Close()
{
#ifdef _WIN64
if ( IsOpen() )
{
#pragma warning(push)
#pragma warning(disable:4311 4312)
ShutdownConnection(reinterpret_cast<SOCKET>(
InterlockedExchangePointer((void**)(&m_hSocket), (void*)INVALID_SOCKET)
));
#pragma warning(pop)
}
#else
if ( IsOpen() )
{
ShutdownConnection(static_cast<SOCKET>(
::InterlockedExchange((LONG*)&m_hSocket, INVALID_SOCKET)
));
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
// AddMembership
bool CSocketHandle::AddMembership(LPCTSTR pszIPAddr, LPCTSTR pszNIC)
{
_ASSERTE( IsOpen() );
if ( IsOpen() )
{
int nType = 0;
socklen_t nOptLen = sizeof(int);
if ( SOCKET_ERROR != getsockopt(m_hSocket, SOL_SOCKET, SO_TYPE, (char*)&nType, &nOptLen))
{
if ( nType == SOCK_DGRAM )
{
// Setup interface for multicast traffic
SockAddrIn mcastAddr;
if (GetAddressInfo(pszIPAddr, NULL, AF_UNSPEC, mcastAddr))
{
SockAddrIn interfAddr;
GetAddressInfo(pszNIC, NULL, mcastAddr.ss_family, interfAddr);
if ( mcastAddr.ss_family == AF_INET )
{
int nTTL = SOCKHANDLE_TTL;
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&nTTL, sizeof(nTTL)))
{
ULONG ulNIC = interfAddr.GetIPAddr();
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IP, IP_MULTICAST_IF,(char *) &ulNIC, sizeof(ulNIC)))
{
ip_mreq mreq = { 0 };
mreq.imr_multiaddr.s_addr = mcastAddr.GetIPAddr();
mreq.imr_interface.s_addr = ulNIC;
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)))
{
return true;
}
}
}
}
else if ( mcastAddr.ss_family == AF_INET6 )
{
int nTTL = SOCKHANDLE_HOPS;
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char*)&nTTL, sizeof(nTTL)))
{
ipv6_mreq mreq6 = { 0 };
IN6_ADDR mcin6 = ((sockaddr_in6*)&mcastAddr)->sin6_addr;
memcpy(&(mreq6.ipv6mr_multiaddr), &mcin6, sizeof(IN6_ADDR));
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (const char*)&mreq6, sizeof(mreq6)))
{
return true;
}
}
}
else
{
// invalid socket option
WSASetLastError(WSAENOPROTOOPT);
}
}
}
else
{
// invalid socket option
WSASetLastError(WSAENOPROTOOPT);
}
}
SetLastError( WSAGetLastError() );
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// DropMembership
bool CSocketHandle::DropMembership(LPCTSTR pszIPAddr, LPCTSTR pszNIC)
{
_ASSERTE( IsOpen() );
if ( IsOpen() )
{
int nType = 0;
socklen_t nOptLen = sizeof(int);
if ( SOCKET_ERROR != getsockopt(m_hSocket, SOL_SOCKET, SO_TYPE, (char*)&nType, &nOptLen))
{
if ( nType == SOCK_DGRAM )
{
SockAddrIn mcastAddr;
if (GetAddressInfo(pszIPAddr, NULL, AF_UNSPEC, mcastAddr))
{
SockAddrIn interfAddr;
GetAddressInfo(pszNIC, NULL, mcastAddr.ss_family, interfAddr);
if ( mcastAddr.ss_family == AF_INET )
{
ip_mreq mreq;
mreq.imr_multiaddr.s_addr = mcastAddr.GetIPAddr();
mreq.imr_interface.s_addr = interfAddr.GetIPAddr();;
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)))
{
return true;
}
}
else if ( mcastAddr.ss_family == AF_INET6 )
{
ipv6_mreq mreq6 = { 0 };
IN6_ADDR mcin6 = ((sockaddr_in6*)&mcastAddr)->sin6_addr;
memcpy(&(mreq6.ipv6mr_multiaddr), &mcin6, sizeof(IN6_ADDR));
if ( SOCKET_ERROR != setsockopt(m_hSocket, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (const char*)&mreq6, sizeof(mreq6)))
{
return true;
}
}
else
{
// invalid socket option
WSASetLastError(WSAENOPROTOOPT);
}
}
}
else
{
// invalid socket option
WSASetLastError(WSAENOPROTOOPT);
}
}
SetLastError( WSAGetLastError() );
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// CreateSocket
bool CSocketHandle::CreateSocket(LPCTSTR pszHostName, LPCTSTR pszServiceName,
int nFamily, int nType, UINT uOptions /* = 0 */)
{
// Socket is already opened
if ( IsOpen() ) {
SetLastError(ERROR_ACCESS_DENIED);
return false;
}
// Create a Socket that is bound to a specific service provider
// nFamily: (AF_INET, AF_INET6)
// nType: (SOCK_STREAM, SOCK_DGRAM)
#ifdef SOCKHANDLE_USE_OVERLAPPED
SOCKET sock = WSASocket(nFamily, nType, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
#else
SOCKET sock = socket(nFamily, nType, IPPROTO_IP);
#endif
if (INVALID_SOCKET != sock)
{
if (uOptions & SO_REUSEADDR)
{
// Inform Windows Sockets provider that a bind on a socket should not be disallowed
// because the desired address is already in use by another socket
BOOL optval = TRUE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof( BOOL ) ) )
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
}
if (SOCK_STREAM == nType)
{
const char chOpt=1;
if(SOCKET_ERROR == setsockopt( sock, IPPROTO_TCP, TCP_NODELAY,&chOpt,sizeof(char)))
{
SetLastError( WSAGetLastError());
closesocket( sock );
return false;
}
}
if (nType == SOCK_DGRAM)
{
if ((uOptions & SO_BROADCAST) && (nFamily == AF_INET))
{
// Inform Windows Sockets provider that broadcast messages are allowed
BOOL optval = TRUE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_BROADCAST, (char *) &optval, sizeof( BOOL ) ) )
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
}
#ifdef SOCKHANDLE_CONFIGBUF
// configure buffer size
socklen_t rcvbuf = BUFFER_SIZE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_RCVBUF, (char *) &rcvbuf, sizeof( int ) ) )
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
#endif
}
// Associate a local address with the socket
SockAddrIn sockAddr;
sockAddr.CreateFrom(pszHostName, pszServiceName, nFamily);
if ( SOCKET_ERROR == bind(sock, sockAddr, (int)sockAddr.Size()))
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
// Listen to the socket, only valid for connection socket (TCP)
if (SOCK_STREAM == nType)
{
if ( SOCKET_ERROR == listen(sock, SOMAXCONN))
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
}
// Success, now we may save this socket
m_hSocket = sock;
}
return (INVALID_SOCKET != sock);
}
///////////////////////////////////////////////////////////////////////////////
// ConnectTo
bool CSocketHandle::ConnectTo(LPCTSTR pszHostName, LPCTSTR pszRemote,
LPCTSTR pszServiceName, int nFamily, int nType)
{
// Socket is already opened
if ( IsOpen() ) {
SetLastError(ERROR_ACCESS_DENIED);
return false;
}
// Create a Socket that is bound to a specific service provider
// nFamily: (AF_INET, AF_INET6)
// nType: (SOCK_STREAM, SOCK_DGRAM)
#ifdef SOCKHANDLE_USE_OVERLAPPED
SOCKET sock = WSASocket(nFamily, nType, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED);
#else
SOCKET sock = socket(nFamily, nType, IPPROTO_IP);
#endif
if (INVALID_SOCKET != sock)
{
// Associate a local address with the socket but let provider assign a port number
SockAddrIn sockAddr;
if (false == sockAddr.CreateFrom(pszHostName, TEXT("0"), nFamily))
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
if ( SOCKET_ERROR == bind(sock, sockAddr, (int)sockAddr.Size()))
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
#ifdef SOCKHANDLE_CONFIGBUF
if (nType == SOCK_DGRAM)
{
// configure buffer size
socklen_t rcvbuf = BUFFER_SIZE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_RCVBUF, (char *) &rcvbuf, sizeof( int ) ) )
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
}
#endif
// Now get destination address & port
sockAddr.CreateFrom( pszRemote, pszServiceName, nFamily );
// try to connect - if fail, server not ready
if (SOCKET_ERROR == connect( sock, sockAddr, (int)sockAddr.Size()))
{
SetLastError( WSAGetLastError() );
closesocket( sock );
return false;
}
// Success, now we may save this socket
m_hSocket = sock;
}
return (INVALID_SOCKET != sock);
}
///////////////////////////////////////////////////////////////////////////////
// Read
DWORD CSocketHandle::Read(LPBYTE lpBuffer, DWORD dwSize, LPSOCKADDR lpAddrIn,
DWORD dwTimeout)
{
_ASSERTE( IsOpen() );
_ASSERTE( lpBuffer != NULL );
if (!IsOpen() || lpBuffer == NULL || dwSize < 1L)
return (DWORD)-1L;
fd_set fdRead = { 0 };
TIMEVAL stTime;
TIMEVAL *pstTime = NULL;
if ( INFINITE != dwTimeout ) {
stTime.tv_sec = dwTimeout/1000;
stTime.tv_usec = (dwTimeout%1000)*1000;
pstTime = &stTime;
}
SOCKET s = GetSocket();
// Set Descriptor
FD_SET( s, &fdRead );
// Select function set read timeout
DWORD dwBytesRead = 0L;
int res = 1;
if ( pstTime != NULL )
res = select((int)s, &fdRead, NULL, NULL, pstTime );
if ( res > 0)
{
if (lpAddrIn)
{
// UDP
socklen_t fromlen = sizeof(SOCKADDR_STORAGE);
res = recvfrom(s, reinterpret_cast<LPSTR>(lpBuffer), dwSize, 0, lpAddrIn, &fromlen);
}
else
{
// TCP
res = recv(s, reinterpret_cast<LPSTR>(lpBuffer), dwSize, 0);
}
if ( res == 0 ) {
WSASetLastError(WSAECONNRESET);
res = SOCKET_ERROR;
}
}
if ( res == SOCKET_ERROR )
{
SetLastError( WSAGetLastError() );
}
dwBytesRead = (DWORD)((res >= 0)?(res) : (-1));
return dwBytesRead;
}
#ifdef WIN32
///////////////////////////////////////////////////////////////////////////////
// ReadEx
DWORD CSocketHandle::ReadEx(LPBYTE lpBuffer, DWORD dwSize, LPSOCKADDR lpAddrIn,
LPWSAOVERLAPPED lpOverlapped, LPWSACOMPLETIONROUTINE lpCompletionRoutine)
{
_ASSERTE( IsOpen() );
_ASSERTE( lpBuffer != NULL );
if (!IsOpen() || lpBuffer == NULL || dwSize < 1L)
return (DWORD)-1L;
SOCKET s = GetSocket();
// Send message to peer
WSABUF wsabuf;
wsabuf.buf = (char FAR*)lpBuffer;
wsabuf.len = dwSize;
// Select function set read timeout
DWORD dwBytesRead = 0L;
DWORD dwFlags = 0L;
int res = 0;
if (lpAddrIn)
{
// UDP
socklen_t fromlen = sizeof(SOCKADDR_STORAGE);
res = WSARecvFrom( s, &wsabuf, 1, &dwBytesRead, &dwFlags, lpAddrIn, &fromlen, lpOverlapped, lpCompletionRoutine);
}
else
{
// TCP
res = WSARecv( s, &wsabuf, 1, &dwBytesRead, &dwFlags, lpOverlapped, lpCompletionRoutine);
}
if ( res == SOCKET_ERROR )
{
res = WSAGetLastError();
if ( res != WSA_IO_PENDING )
{
dwBytesRead = (DWORD)-1L;
SetLastError( res );
}
}
return dwBytesRead;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Write
DWORD CSocketHandle::Write(const LPBYTE lpBuffer, DWORD dwCount,
const LPSOCKADDR lpAddrIn, DWORD dwTimeout)
{
_ASSERTE( IsOpen() );
_ASSERTE( NULL != lpBuffer );
// validate params
if (!IsOpen() || NULL == lpBuffer)
return (DWORD)-1L;
fd_set fdWrite = { 0 };
TIMEVAL stTime;
TIMEVAL *pstTime = NULL;
if ( INFINITE != dwTimeout ) {
stTime.tv_sec = dwTimeout/1000;
stTime.tv_usec = (dwTimeout%1000)*1000;
pstTime = &stTime;
}
SOCKET s = GetSocket();
// Set Descriptor
FD_SET( s, &fdWrite );
// Select function set write timeout
DWORD dwBytesWritten = 0L;
int res = 1;
if ( pstTime != NULL )
res = select((int)s, NULL, &fdWrite, NULL, pstTime );
if ( res > 0)
{
// Send message to peer
if (lpAddrIn)
{
// UDP
res = sendto( s, reinterpret_cast<LPCSTR>(lpBuffer), dwCount, 0, lpAddrIn, sizeof(SOCKADDR_STORAGE));
}
else
{
// TCP
res = send( s, reinterpret_cast<LPCSTR>(lpBuffer), dwCount, 0);
}
}
if ( res == SOCKET_ERROR )
{
SetLastError( WSAGetLastError() );
}
dwBytesWritten = (DWORD)((res >= 0)?(res) : (-1));
return dwBytesWritten;
}
#ifdef WIN32
///////////////////////////////////////////////////////////////////////////////
// WriteEx
DWORD CSocketHandle::WriteEx(const LPBYTE lpBuffer, DWORD dwCount,
const LPSOCKADDR lpAddrIn,
LPWSAOVERLAPPED lpOverlapped, LPWSACOMPLETIONROUTINE lpCompletionRoutine)
{
_ASSERTE( IsOpen() );
_ASSERTE( NULL != lpBuffer );
// validate params
if (!IsOpen() || NULL == lpBuffer)
return (DWORD)-1L;
SOCKET s = GetSocket();
// Select function set write timeout
DWORD dwBytesWritten = 0L;
int res = 0;
// Send message to peer
WSABUF wsabuf;
wsabuf.buf = (char FAR*) lpBuffer;
wsabuf.len = dwCount;
if (lpAddrIn)
{
// UDP
res = WSASendTo( s, &wsabuf, 1, &dwBytesWritten, 0, lpAddrIn, sizeof(SOCKADDR_STORAGE),
lpOverlapped, lpCompletionRoutine);
}
else // TCP
res = WSASend( s, &wsabuf, 1, &dwBytesWritten, 0, lpOverlapped, lpCompletionRoutine);
if ( res == SOCKET_ERROR )
{
res = WSAGetLastError();
if ( res != WSA_IO_PENDING )
{
dwBytesWritten = (DWORD)-1L;
SetLastError( res );
}
}
return dwBytesWritten;
}
#endif
#ifdef WIN32
///////////////////////////////////////////////////////////////////////////////
// IOControl
bool CSocketHandle::IOControl(DWORD dwIoCode, LPBYTE lpInBuffer, DWORD cbInBuffer,
LPBYTE lpOutBuffer, DWORD cbOutBuffer,
LPDWORD lpcbBytesReturned, LPWSAOVERLAPPED lpOverlapped,
LPWSACOMPLETIONROUTINE lpCompletionRoutine)
{
_ASSERTE( IsOpen() );
// validate params
if ( !IsOpen() ) {
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
int res;
SOCKET s = GetSocket();
res = WSAIoctl(s, dwIoCode, lpInBuffer, cbInBuffer, lpOutBuffer, cbOutBuffer,
lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
if ( res == SOCKET_ERROR )
{
SetLastError( WSAGetLastError() );
}
return ( res != SOCKET_ERROR );
}
///////////////////////////////////////////////////////////////////////////////
// GetTransferOverlappedResult
bool CSocketHandle::GetTransferOverlappedResult(LPWSAOVERLAPPED lpOverlapped, LPDWORD lpcbTransfer,
bool bWait /*= true*/, LPDWORD lpdwFlags /*= NULL*/)
{
_ASSERTE( IsOpen() );
_ASSERTE( NULL != lpOverlapped );
// validate params
if (!IsOpen() || NULL == lpOverlapped) {
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
SOCKET s = GetSocket();
DWORD dwFlags = 0;
if ( lpdwFlags == NULL )
lpdwFlags = &dwFlags;
BOOL bRet = WSAGetOverlappedResult( s, lpOverlapped, lpcbTransfer, bWait, lpdwFlags );
if ( !bRet )
{
SetLastError( WSAGetLastError() );
}
return (bRet != FALSE);
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Utility functions
///////////////////////////////////////////////////////////////////////////////
// InitLibrary
bool CSocketHandle::InitLibrary(WORD wVersion)
{
#ifdef WIN32
WSADATA WSAData = { 0 };
return ( 0 == WSAStartup( wVersion, &WSAData ) );
#else
return true;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// ReleaseLibrary
bool CSocketHandle::ReleaseLibrary()
{
#ifdef WIN32
return ( 0 == WSACleanup() );
#else
return true;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// WaitForConnection
SOCKET CSocketHandle::WaitForConnection(SOCKET sock)
{
return accept(sock, 0, 0);
}
///////////////////////////////////////////////////////////////////////////////
// ShutdownConnection
bool CSocketHandle::ShutdownConnection(SOCKET sock)
{
shutdown(sock, SD_BOTH);
return ( 0 == closesocket( sock ));
}
static unsigned char chMinClassA_IP [] = { 1, 0, 0, 0 } ;
static unsigned char chMinClassD_IP [] = { 224, 0, 0, 0 } ;
static unsigned char chMaxClassD_IP [] = { 239, 255, 255, 255 } ;
///////////////////////////////////////////////////////////////////////////////
// IsUnicastIP
bool CSocketHandle::IsUnicastIP( ULONG ulAddr )
{
return (((unsigned char *) & ulAddr) [0] >= chMinClassA_IP [0] &&
((unsigned char *) & ulAddr) [0] < chMinClassD_IP [0]) ;
}
///////////////////////////////////////////////////////////////////////////////
// IsMulticastIP
bool CSocketHandle::IsMulticastIP( ULONG ulAddr )
{
return (((unsigned char *) & ulAddr) [0] >= chMinClassD_IP [0] &&
((unsigned char *) & ulAddr) [0] <= chMaxClassD_IP [0]) ;
}
///////////////////////////////////////////////////////////////////////////////
// FormatIP
bool CSocketHandle::FormatIP(LPTSTR pszIPAddr, UINT nSize, ULONG ulAddr, bool bFmtHost)
{
if ( pszIPAddr && nSize > 8)
{
if ( bFmtHost )
ulAddr = htonl( ulAddr );
// Create Address string
return (SUCCEEDED(StringCchPrintf(pszIPAddr, nSize, TEXT("%u.%u.%u.%u"),
(UINT)(((PBYTE) &ulAddr)[0]),
(UINT)(((PBYTE) &ulAddr)[1]),
(UINT)(((PBYTE) &ulAddr)[2]),
(UINT)(((PBYTE) &ulAddr)[3]))));
}
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// FormatIP
bool CSocketHandle::FormatIP(LPTSTR pszIPAddr, UINT nSize, const SockAddrIn& addrIn)
{
if ( pszIPAddr && nSize > 8)
{
const void* addr;
char szIPAddr[MAX_PATH] = { 0 };
if (addrIn.ss_family == AF_INET) {
addr = &((const sockaddr_in*)&addrIn)->sin_addr;
} else {
addr = &((const sockaddr_in6*)&addrIn)->sin6_addr;
}
if (inet_ntop(addrIn.ss_family, addr, szIPAddr, MAX_PATH) != NULL)
{
#ifdef _UNICODE
return (0 != ansi2uni(CP_ACP,szIPAddr,pszIPAddr));
#else
::StringCbCopyA(pszIPAddr, nSize, szIPAddr);
return true;
#endif
}
}
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetPortNumber
USHORT CSocketHandle::GetPortNumber( LPCTSTR pszServiceName )
{
LPSERVENT lpservent;
USHORT nPort = 0;
if ( _istdigit( pszServiceName[0] ) ) {
nPort = (USHORT) _ttoi( pszServiceName );
}
else {
#ifdef _UNICODE
char pstrService[HOSTNAME_SIZE] = { 0 };
uni2ansi(CP_ACP,(LPTSTR)pszServiceName,pstrService);
#else
LPCTSTR pstrService = pszServiceName;
#endif
// Convert network byte order to host byte order
if ( (lpservent = getservbyname( pstrService, NULL )) != NULL )
nPort = ntohs( lpservent->s_port );
}
return nPort;
}
///////////////////////////////////////////////////////////////////////////////
// GetIPAddress
ULONG CSocketHandle::GetIPAddress( LPCTSTR pszHostName )
{
LPHOSTENT lphostent;
ULONG uAddr = INADDR_NONE;
TCHAR szLocal[HOSTNAME_SIZE] = { 0 };
// if no name specified, get local
if ( NULL == pszHostName || !pszHostName[0])
{
GetLocalName(szLocal, HOSTNAME_SIZE);
pszHostName = szLocal;
}
#ifdef _UNICODE
char pstrHost[HOSTNAME_SIZE] = { 0 };
uni2ansi(CP_ACP,(LPTSTR)pszHostName,pstrHost);
#else
LPCTSTR pstrHost = pszHostName;
#endif
// Check for an Internet Protocol dotted address string
uAddr = inet_addr( pstrHost );
if ( (INADDR_NONE == uAddr) && (strcmp( pstrHost, "255.255.255.255" )) )
{
// It's not an address, then try to resolve it as a hostname
if ( (lphostent = gethostbyname( pstrHost )) != NULL )
uAddr = *((ULONG *) lphostent->h_addr_list[0]);
}
return ntohl( uAddr );
}
///////////////////////////////////////////////////////////////////////////////
// GetLocalName
bool CSocketHandle::GetLocalName(LPTSTR pszName, UINT nSize)
{
if (pszName != NULL && nSize > 0)
{
char szHost[HOSTNAME_SIZE] = { 0 };
// get host name, if fail, SetLastError is set
if (SOCKET_ERROR != gethostname(szHost, sizeof(szHost)))
{
struct hostent* hp;
hp = gethostbyname(szHost);
if (hp != NULL) {
::StringCbCopyA(szHost, HOSTNAME_SIZE, hp->h_name);
}
// check if user provide enough buffer
size_t cbLength = 0;
::StringCbLengthA(szHost, HOSTNAME_SIZE, &cbLength);
if ( cbLength > nSize )
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode conversion
#ifdef _UNICODE
return (0 != ansi2uni(CP_ACP,szHost,pszName));
#else
::StringCbCopyA(pszName, nSize, szHost);
return true;
#endif
}
else
SetLastError( WSAGetLastError() );
}
else