-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSocketMaster2.cls
1936 lines (1541 loc) · 65.9 KB
/
CSocketMaster2.cls
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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
Persistable = 0 'NotPersistable
DataBindingBehavior = 0 'vbNone
DataSourceBehavior = 0 'vbNone
MTSTransactionMode = 0 'NotAnMTSObject
END
Attribute VB_Name = "CSocketMaster"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
'********************************************************************************
'
'Name.......... CSocketMaster
'File.......... CSocketMaster.cls
'Version....... 1.2
'Dependencies.. Requires modSocketMaster.bas code module
'Description... Winsock api implementation class
'Author........ Emiliano Scavuzzo <[email protected]>
'Date.......... June, 28th 2004
'Copyright (c) 2004 by Emiliano Scavuzzo
'Rosario, Argentina
'
'Based on CSocket by Oleg Gdalevich
'Subclassing based on WinSubHook2 by Paul Caton <[email protected]>
'
'********************************************************************************
'Use AutoBind for instant telnet server
Option Explicit
Dim dodebug As Boolean, automatic As Boolean, isserver As Boolean
'==============================================================================
'API FUNCTIONS
'==============================================================================
Private Declare Function api_socket Lib "ws2_32.dll" Alias "socket" (ByVal af As Long, ByVal s_type As Long, ByVal Protocol As Long) As Long
Private Declare Function api_GlobalLock Lib "kernel32" Alias "GlobalLock" (ByVal hMem As Long) As Long
Private Declare Function api_GlobalUnlock Lib "kernel32" Alias "GlobalUnlock" (ByVal hMem As Long) As Long
Private Declare Function api_htons Lib "ws2_32.dll" Alias "htons" (ByVal hostshort As Integer) As Integer
Private Declare Function api_ntohs Lib "ws2_32.dll" Alias "ntohs" (ByVal netshort As Integer) As Integer
Private Declare Function api_connect Lib "ws2_32.dll" Alias "connect" (ByVal s As Long, ByRef name As sockaddr_in, ByVal namelen As Long) As Long
Private Declare Function api_gethostname Lib "ws2_32.dll" Alias "gethostname" (ByVal host_name As String, ByVal namelen As Long) As Long
Private Declare Function api_gethostbyname Lib "ws2_32.dll" Alias "gethostbyname" (ByVal host_name As String) As Long
Private Declare Function api_bind Lib "ws2_32.dll" Alias "bind" (ByVal s As Long, ByRef name As sockaddr_in, ByVal namelen As Long) As Long
Private Declare Function api_getsockname Lib "ws2_32.dll" Alias "getsockname" (ByVal s As Long, ByRef name As sockaddr_in, ByRef namelen As Long) As Long
Private Declare Function api_getpeername Lib "ws2_32.dll" Alias "getpeername" (ByVal s As Long, ByRef name As sockaddr_in, ByRef namelen As Long) As Long
Private Declare Function api_inet_addr Lib "ws2_32.dll" Alias "inet_addr" (ByVal cp As String) As Long
Private Declare Function api_send Lib "ws2_32.dll" Alias "send" (ByVal s As Long, ByRef buf As Any, ByVal buflen As Long, ByVal Flags As Long) As Long
Private Declare Function api_sendto Lib "ws2_32.dll" Alias "sendto" (ByVal s As Long, ByRef buf As Any, ByVal buflen As Long, ByVal Flags As Long, ByRef toaddr As sockaddr_in, ByVal tolen As Long) As Long
Private Declare Function api_getsockopt Lib "ws2_32.dll" Alias "getsockopt" (ByVal s As Long, ByVal level As Long, ByVal optname As Long, optval As Any, optlen As Long) As Long
Private Declare Function api_setsockopt Lib "ws2_32.dll" Alias "setsockopt" (ByVal s As Long, ByVal level As Long, ByVal optname As Long, optval As Any, ByVal optlen As Long) As Long
Private Declare Function api_recv Lib "ws2_32.dll" Alias "recv" (ByVal s As Long, ByRef buf As Any, ByVal buflen As Long, ByVal Flags As Long) As Long
Private Declare Function api_recvfrom Lib "ws2_32.dll" Alias "recvfrom" (ByVal s As Long, ByRef buf As Any, ByVal buflen As Long, ByVal Flags As Long, ByRef from As sockaddr_in, ByRef fromlen As Long) As Long
Private Declare Function api_WSACancelAsyncRequest Lib "ws2_32.dll" Alias "WSACancelAsyncRequest" (ByVal hAsyncTaskHandle As Long) As Long
Private Declare Function api_listen Lib "ws2_32.dll" Alias "listen" (ByVal s As Long, ByVal backlog As Long) As Long
Private Declare Function api_accept Lib "ws2_32.dll" Alias "accept" (ByVal s As Long, ByRef addr As sockaddr_in, ByRef addrlen As Long) As Long
Private Declare Function api_inet_ntoa Lib "ws2_32.dll" Alias "inet_ntoa" (ByVal inn As Long) As Long
Private Declare Function api_ioctlsocket Lib "ws2_32.dll" Alias "ioctlsocket" (ByVal s As Long, ByVal cmd As Long, ByRef argp As Long) As Long
Private Declare Function api_closesocket Lib "ws2_32.dll" Alias "closesocket" (ByVal s As Long) As Long
'Private Declare Function api_gethostbyaddr Lib "ws2_32.dll" Alias "gethostbyaddr" (addr As Long, ByVal addr_len As Long, ByVal addr_type As Long) As Long
'==============================================================================
'CONSTANTS
'==============================================================================
Public Enum SockState
sckClosed = 0
sckOpen
sckListening
sckConnectionPending
sckResolvingHost
sckHostResolved
sckConnecting
sckConnected
sckClosing
sckError
End Enum
Private Const SOMAXCONN As Long = 5
Public Enum ProtocolConstants
sckTCPProtocol = 0
sckUDPProtocol = 1
End Enum
Private Const MSG_PEEK As Long = &H2
'==============================================================================
'EVENTS
'==============================================================================
Public Event CloseSck()
Public Event Connect()
Public Event ConnectionRequest(ByVal requestID As Long)
Public Event DataArrival(ByVal bytesTotal As Long)
Public Event DataRecieved(ByVal Data As String)
Public Event Error(ByVal Number As Integer, Description As String, ByVal sCode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
Public Event SendComplete()
Public Event SendProgress(ByVal bytesSent As Long, ByVal bytesRemaining As Long)
'==============================================================================
'MEMBER VARIABLES
'==============================================================================
Private m_lngSocketHandle As Long 'socket handle
Private m_enmState As SockState 'socket state
Private m_strTag As String 'tag
Private m_strRemoteHost As String 'remote host
Private m_lngRemotePort As Long 'remote port
Private m_strRemoteHostIP As String 'remote host ip
Private m_lngLocalPort As Long 'local port
Private m_lngLocalPortBind As Long 'temporary local port
Private m_strLocalIP As String 'local IP
Private m_enmProtocol As ProtocolConstants 'protocol used (TCP / UDP)
Private m_lngMemoryPointer As Long 'memory pointer used as buffer when resolving host
Private m_lngMemoryHandle As Long 'buffer memory handle
Private m_lngSendBufferLen As Long 'winsock buffer size for sends
Private m_lngRecvBufferLen As Long 'winsock buffer size for receives
Private m_strSendBuffer As String 'local incoming buffer
Private m_strRecvBuffer As String 'local outgoing buffer
Private m_blnAcceptClass As Boolean 'if True then this is an Accept socket class
Private m_colWaitingResolutions As Collection 'hosts waiting to be resolved by the system
Public Delimeter As String
' **** WARNING WARNING WARNING WARNING ******
'This sub MUST be the first on the class. DO NOT attempt
'to change it's location or the code will CRASH.
'This sub receives system messages from our WndProc.
Public Sub WndProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long)
Select Case uMsg
Case RESOLVE_MESSAGE
PostResolution wParam, HiWord(lParam)
Case SOCKET_MESSAGE
PostSocket LoWord(lParam), HiWord(lParam)
End Select
End Sub
Private Sub Class_Initialize()
'socket's handle default value
m_lngSocketHandle = INVALID_SOCKET
'initiate resolution collection
Set m_colWaitingResolutions = New Collection
'initiate processes and winsock service
modSocketMaster.InitiateProcesses
dodebug = True
End Sub
Private Sub Class_Terminate()
'clean hostname resolution system
CleanResolutionSystem
'destroy socket if it exists
If Not m_blnAcceptClass Then DestroySocket
'clean processes and finish winsock service
modSocketMaster.FinalizeProcesses
'clean resolution collection
Set m_colWaitingResolutions = Nothing
End Sub
'==============================================================================
'PROPERTIES
'==============================================================================
Public Property Get RemotePort() As Long
RemotePort = m_lngRemotePort
End Property
Public Property Let RemotePort(ByVal lngPort As Long)
If m_enmProtocol = sckTCPProtocol And m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.RemotePort", "Invalid operation at current state"
End If
If lngPort < 0 Or lngPort > 65535 Then
Err.Raise sckInvalidArg, "CSocketMaster.RemotePort", "The argument passed to a function was not in the correct format or in the specified range."
Else
m_lngRemotePort = lngPort
End If
End Property
Public Property Get RemoteHost() As String
RemoteHost = m_strRemoteHost
End Property
Public Property Let RemoteHost(ByVal strHost As String)
If m_enmProtocol = sckTCPProtocol And m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.RemoteHost", "Invalid operation at current state"
End If
m_strRemoteHost = strHost
End Property
Public Property Get RemoteHostIP() As String
RemoteHostIP = m_strRemoteHostIP
End Property
Public Property Get LocalPort() As Long
If m_lngLocalPortBind = 0 Then
LocalPort = m_lngLocalPort
Else
LocalPort = m_lngLocalPortBind
End If
End Property
Public Property Let LocalPort(ByVal lngPort As Long)
If m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.LocalPort", "Invalid operation at current state"
End If
If lngPort < 0 Or lngPort > 65535 Then
Err.Raise sckInvalidArg, "CSocketMaster.LocalPort", "The argument passed to a function was not in the correct format or in the specified range."
Else
m_lngLocalPort = lngPort
End If
End Property
Public Property Get State() As SockState
State = m_enmState
End Property
Public Property Get LocalHostName() As String
LocalHostName = GetLocalHostName
End Property
Public Property Get LocalIP() As String
If m_enmState = sckConnected Then
LocalIP = m_strLocalIP
Else
LocalIP = GetLocalIP
End If
End Property
Public Property Get BytesReceived() As Long
If m_enmProtocol = sckTCPProtocol Then
BytesReceived = Len(m_strRecvBuffer)
Else
BytesReceived = GetBufferLenUDP
End If
End Property
Public Property Get SocketHandle() As Long
SocketHandle = m_lngSocketHandle
End Property
Public Property Get PrintDebug() As Boolean
PrintDebug = dodebug
End Property
Public Property Let PrintDebug(ByVal temp As Boolean)
dodebug = temp
Silent = temp
End Property
Public Property Get AutoAccept() As Boolean
AutoAccept = automatic
End Property
Public Property Let AutoAccept(ByVal temp As Boolean)
automatic = temp
End Property
Public Property Get Tag() As String
Tag = m_strTag
End Property
Public Property Let Tag(ByVal strTag As String)
m_strTag = strTag
End Property
Public Property Get Protocol() As ProtocolConstants
Protocol = m_enmProtocol
End Property
Public Property Let Protocol(ByVal enmProtocol As ProtocolConstants)
If m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.Protocol", "Invalid operation at current state"
Else
m_enmProtocol = enmProtocol
End If
End Property
'Destroys the socket if it exists and unregisters it
'from control list.
Private Sub DestroySocket()
If Not m_lngSocketHandle = INVALID_SOCKET Then
Dim lngResult As Long
lngResult = api_closesocket(m_lngSocketHandle)
If lngResult = SOCKET_ERROR Then
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.DestroySocket", GetErrorDescription(lngErrorCode)
Else
If dodebug Then Debug.Print "OK Destroyed socket " & m_lngSocketHandle
modSocketMaster.UnregisterSocket m_lngSocketHandle
m_lngSocketHandle = INVALID_SOCKET
End If
End If
End Sub
Public Sub CloseSck()
If m_lngSocketHandle = INVALID_SOCKET Then Exit Sub
m_enmState = sckClosing: If dodebug Then Debug.Print "STATE: sckClosing"
CleanResolutionSystem
DestroySocket
m_lngLocalPortBind = 0
m_strRemoteHostIP = ""
m_strRecvBuffer = ""
m_strSendBuffer = ""
m_lngSendBufferLen = 0
m_lngRecvBufferLen = 0
m_enmState = sckClosed: If dodebug Then Debug.Print "STATE: sckClosed"
End Sub
'Tries to create a socket if there isn't one yet and registers
'it to the control list.
'Returns TRUE if it has success
Private Function SocketExists() As Boolean
SocketExists = True
Dim lngResult As Long
Dim lngErrorCode As Long
'check if there is a socket already
If m_lngSocketHandle = INVALID_SOCKET Then
'decide what kind of socket we are creating, TCP or UDP
If m_enmProtocol = sckTCPProtocol Then
lngResult = api_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
Else
lngResult = api_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
End If
If lngResult = INVALID_SOCKET Then
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
If dodebug Then Debug.Print "ERROR trying to create socket"
SocketExists = False
lngErrorCode = Err.LastDllError
Dim blnCancelDisplay As Boolean
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.SocketExists", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.SocketExists"
Else
If dodebug Then Debug.Print "OK Created socket: " & lngResult
m_lngSocketHandle = lngResult
'set and get some socket options
ProcessOptions
SocketExists = modSocketMaster.RegisterSocket(m_lngSocketHandle, ObjPtr(Me), True)
End If
End If
End Function
'Tries to connect to RemoteHost if it was passed, or uses
'm_strRemoteHost instead. If it is a hostname tries to
'resolve it first.
Public Sub Connect(Optional RemoteHost As Variant, Optional RemotePort As Variant)
If m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.Connect", "Invalid operation at current state"
End If
If Not IsMissing(RemoteHost) Then
m_strRemoteHost = CStr(RemoteHost)
End If
'for some reason we get a GPF if we try to
'resolve a null string, so we replace it with
'an empty string
If m_strRemoteHost = vbNullString Then
m_strRemoteHost = ""
End If
'check if RemotePort is a number between 1 and 65535
If Not IsMissing(RemotePort) Then
If IsNumeric(RemotePort) Then
If CLng(RemotePort) > 65535 Or CLng(RemotePort) < 1 Then
Err.Raise sckInvalidArg, "CSocketMaster.Connect", "The argument passed to a function was not in the correct format or in the specified range."
Else
m_lngRemotePort = CLng(RemotePort)
End If
Else
Err.Raise sckUnsupported, "CSocketMaster.Connect", "Unsupported variant type."
End If
End If
'create a socket if there isn't one yet
If Not SocketExists Then Exit Sub
'Here we bind the socket
If Not BindInternal Then Exit Sub
'If we are using UDP we just exit silently.
'Remember UDP is a connectionless protocol.
If m_enmProtocol = sckUDPProtocol Then
m_enmState = sckOpen: If dodebug Then Debug.Print "STATE: sckOpen"
Exit Sub
End If
'try to get a 32 bits long that is used to identify a host
Dim lngAddress As Long
lngAddress = ResolveIfHostname(m_strRemoteHost)
'We've got two options here:
'1) m_strRemoteHost was an IP, so a resolution wasn't
' necessary, and now lngAddress is a 32 bits long and
' we proceed to connect.
'2) m_strRemoteHost was a hostname, so a resolution was
' necessary and it's taking place right now. We leave
' silently.
If lngAddress <> vbNull Then
ConnectToIP lngAddress, 0
End If
isserver = False
End Sub
Public Function IsTheServer() As Boolean
IsTheServer = isserver And State = sckConnected
End Function
Public Function IsTheClient() As Boolean
IsTheClient = State = sckConnected And Not isserver
End Function
'When the system resolves a hostname in asynchronous way we
'call this function to decide what to do with the result.
Private Sub PostResolution(ByVal lngAsynHandle As Long, ByVal lngErrorCode As Long)
'erase that record from the collection since we won't need it any longer
m_colWaitingResolutions.Remove "R" & lngAsynHandle
UnregisterResolution lngAsynHandle
If m_enmState <> sckResolvingHost Then Exit Sub
If lngErrorCode = 0 Then 'if there weren't errors trying to resolve the hostname
m_enmState = sckHostResolved: If dodebug Then Debug.Print "STATE: sckHostResolved"
Dim udtHostent As HOSTENT
Dim lngPtrToIP As Long
Dim arrIpAddress(1 To 4) As Byte
Dim lngRemoteHostAddress As Long
Dim count As Integer
Dim strIpAddress As String
api_CopyMemory udtHostent, ByVal m_lngMemoryPointer, LenB(udtHostent)
api_CopyMemory lngPtrToIP, ByVal udtHostent.hAddrList, 4
api_CopyMemory arrIpAddress(1), ByVal lngPtrToIP, 4
api_CopyMemory lngRemoteHostAddress, ByVal lngPtrToIP, 4
'free memory, won't need it any longer
FreeMemory
'We turn the 32 bits long into a readable string.
'Note: we don't need this string. I put this here just
'in case you need it.
For count = 1 To 4
strIpAddress = strIpAddress & arrIpAddress(count) & "."
Next
strIpAddress = Left$(strIpAddress, Len(strIpAddress) - 1)
ConnectToIP lngRemoteHostAddress, 0
Else 'there were errors trying to resolve the hostname
'free buffer memory
FreeMemory
ConnectToIP vbNull, lngErrorCode
End If
End Sub
'This procedure is called by the WindowProc callback function.
'The lngEventID argument is an ID of the network event
'occurred for the socket. The lngErrorCode argument contains
'an error code only if an error was occurred during an
'asynchronous execution.
Private Sub PostSocket(ByVal lngEventID As Long, ByVal lngErrorCode As Long)
Dim blnCancelDisplay As Boolean ', tempstr As String
'handle any possible error
If lngErrorCode <> 0 Then
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.PostSocket", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.PostSocket"
Exit Sub
End If
Dim udtSockAddr As sockaddr_in
Dim lngResult As Long
Dim lngBytesReceived As Long
Select Case lngEventID
'======================================================================
Case FD_CONNECT
'Arrival of this message means that the connection initiated by the call
'of the connect Winsock API function was successfully established.
If dodebug Then Debug.Print "FD_CONNECT " & m_lngSocketHandle
If m_enmState <> sckConnecting Then
If dodebug Then Debug.Print "WARNING: Omitting FD_CONNECT"
Exit Sub
End If
'Get the local parameters
GetLocalInfo m_lngSocketHandle, m_lngLocalPortBind, m_strLocalIP
'Get the connection local end-point parameters
GetRemoteInfo m_lngSocketHandle, m_lngRemotePort, m_strRemoteHostIP, m_strRemoteHost
m_enmState = sckConnected: If dodebug Then Debug.Print "STATE: sckConnected"
RaiseEvent Connect
'======================================================================
Case FD_WRITE
'This message means that the socket in a write-able
'state, that is, buffer for outgoing data of the transport
'service is empty and ready to receive data to send through
'the network.
If dodebug Then Debug.Print "FD_WRITE " & m_lngSocketHandle
If m_enmState <> sckConnected Then
If dodebug Then Debug.Print "WARNING: Omitting FD_WRITE"
Exit Sub
End If
If Len(m_strSendBuffer) > 0 Then
SendBufferedData
End If
'======================================================================
Case FD_READ
'Some data has arrived for this socket.
If dodebug Then Debug.Print "FD_READ " & m_lngSocketHandle
If m_enmProtocol = sckTCPProtocol Then
If m_enmState <> sckConnected Then
If dodebug Then Debug.Print "WARNING: Omitting FD_READ"
Exit Sub
End If
'Call the RecvDataToBuffer function that move arrived data
'from the Winsock buffer to the local one and returns number
'of bytes received.
lngBytesReceived = RecvDataToBuffer
If lngBytesReceived > 0 Then
HandleDataArrival
RaiseEvent DataArrival(Len(m_strRecvBuffer))
End If
Else 'UDP protocol
If m_enmState <> sckOpen Then
If dodebug Then Debug.Print "WARNING: Omitting FD_READ"
Exit Sub
End If
'If we use UDP we don't remove data from winsock buffer.
'We just let the user know the amount received so
'he/she can decide what to do.
lngBytesReceived = GetBufferLenUDP
If lngBytesReceived > 0 Then
HandleDataArrival
RaiseEvent DataArrival(lngBytesReceived)
End If
'Now the buffer is emptied no matter what the user
'dicided to do with the received data
EmptyBuffer
End If
'======================================================================
Case FD_ACCEPT
'When the socket is in a listening state, arrival of this message
'means that a connection request was received. Call the accept
'Winsock API function in oreder to create a new socket for the
'requested connection.
If dodebug Then Debug.Print "FD_ACCEPT " & m_lngSocketHandle
If m_enmState <> sckListening Then
If dodebug Then Debug.Print "WARNING: Omitting FD_ACCEPT"
Exit Sub
End If
lngResult = api_accept(m_lngSocketHandle, udtSockAddr, LenB(udtSockAddr))
If lngResult = INVALID_SOCKET Then
lngErrorCode = Err.LastDllError
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.PostSocket", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.PostSocket"
Else
'We assign a temporal instance of CSocketMaster to
'handle this new socket until user accepts (or not)
'the new connection
modSocketMaster.RegisterAccept lngResult
'We change remote info before firing ConnectionRequest
'event so the user can see which host is trying to
'connect.
Dim lngTempRP As Long
Dim strTempRHIP As String
Dim strTempRH As String
lngTempRP = m_lngRemotePort
strTempRHIP = m_strRemoteHostIP
strTempRH = m_strRemoteHost
GetRemoteInfo lngResult, m_lngRemotePort, m_strRemoteHostIP, m_strRemoteHost
If dodebug Then Debug.Print "OK Accepted socket: " & lngResult
If automatic Then
CloseSck
Accept lngResult
End If
RaiseEvent ConnectionRequest(lngResult)
'we return original info
If m_enmState = sckListening Then
m_lngRemotePort = lngTempRP
m_strRemoteHostIP = strTempRHIP
m_strRemoteHost = strTempRH
End If
'This is very important. If the connection wasn't accepted
'we must close the socket.
If IsAcceptRegistered(lngResult) Then
api_closesocket lngResult
modSocketMaster.UnregisterSocket lngResult
modSocketMaster.UnregisterAccept lngResult
If dodebug Then Debug.Print "OK Closed accepted socket: " & lngResult
End If
End If
'======================================================================
Case FD_CLOSE
'This message means that the remote host is closing the conection
If dodebug Then Debug.Print "FD_CLOSE " & m_lngSocketHandle
If m_enmState <> sckConnected Then
If dodebug Then Debug.Print "WARNING: Omitting FD_CLOSE"
Exit Sub
End If
m_enmState = sckClosing: If dodebug Then Debug.Print "STATE: sckClosing"
If automatic Then CloseSck
RaiseEvent CloseSck
End Select
End Sub
'Connect to a given 32 bits long ip
Private Sub ConnectToIP(ByVal lngRemoteHostAddress As Long, ByVal lngErrorCode As Long)
Dim blnCancelDisplay As Boolean
'Check and handle errors
If lngErrorCode <> 0 Then
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.ConnectToIP", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.ConnectToIP"
Exit Sub
End If
If dodebug Then Debug.Print "OK Connecting to: " + m_strRemoteHost + " " + m_strRemoteHostIP
m_enmState = sckConnecting: If dodebug Then Debug.Print "STATE: sckConnecting"
Dim udtSockAddr As sockaddr_in
Dim lngResult As Long
'Build the sockaddr_in structure to pass it to the connect
'Winsock API function as an address of the remote host.
With udtSockAddr
.sin_addr = lngRemoteHostAddress
.sin_family = AF_INET
.sin_port = api_htons(modSocketMaster.UnsignedToInteger(m_lngRemotePort))
End With
'Call the connect Winsock API function in order to establish connection.
lngResult = api_connect(m_lngSocketHandle, udtSockAddr, LenB(udtSockAddr))
'Check and handle errors
If lngResult = SOCKET_ERROR Then
lngErrorCode = Err.LastDllError
If lngErrorCode <> WSAEWOULDBLOCK Then
If lngErrorCode = WSAEADDRNOTAVAIL Then
Err.Raise WSAEADDRNOTAVAIL, "CSocketMaster.ConnectToIP", GetErrorDescription(WSAEADDRNOTAVAIL)
Else
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.ConnectToIP", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.ConnectToIP"
End If
End If
End If
End Sub
Public Function AutoBind(Optional Port As Long = 21, Optional doListen As Boolean, Optional AutoAccept As Boolean, Optional ConnectToIP As Variant, Optional doConnect As Boolean, Optional Separator As String = "@") As Long
Dim temp As Long
temp = Port
Do Until TryBind(temp)
temp = temp + 1
Loop
AutoBind = temp
automatic = AutoAccept
Delimeter = Separator
If doListen Then
Listen
ElseIf doConnect Then
Connect ConnectToIP, Port
End If
End Function
Private Function TryBind(Port As Long) As Boolean
On Error Resume Next
Bind Port
TryBind = True
End Function
Public Sub Bind(Optional LocalPort As Variant, Optional LocalIP As Variant)
If m_enmState <> sckClosed Then
Err.Raise sckInvalidOp, "CSocketMaster.Bind", "Invalid operation at current state"
End If
If BindInternal(LocalPort, LocalIP) Then
m_enmState = sckOpen: If dodebug Then Debug.Print "STATE: sckOpen"
End If
End Sub
'This function binds a socket to a local port and IP.
'Retunrs TRUE if it has success.
Private Function BindInternal(Optional ByVal varLocalPort As Variant, Optional ByVal varLocalIP As Variant) As Boolean
If m_enmState = sckOpen Then
BindInternal = True
Exit Function
End If
Dim lngLocalPortInternal As Long
Dim strLocalHostInternal As String
Dim strIP As String
Dim lngAddressInternal As Long
Dim lngResult As Long
Dim lngErrorCode As Long
BindInternal = False
'Check if varLocalPort is a number between 0 and 65535
If Not IsMissing(varLocalPort) Then
If IsNumeric(varLocalPort) Then
If varLocalPort < 0 Or varLocalPort > 65535 Then
BindInternal = False
Err.Raise sckInvalidArg, "CSocketMaster.BindInternal", "The argument passed to a function was not in the correct format or in the specified range."
Else
lngLocalPortInternal = CLng(varLocalPort)
End If
Else
BindInternal = False
Err.Raise sckUnsupported, "CSocketMaster.BindInternal", "Unsupported variant type."
End If
Else
lngLocalPortInternal = m_lngLocalPort
End If
If Not IsMissing(varLocalIP) Then
If varLocalIP <> vbNullString Then
strLocalHostInternal = CStr(varLocalIP)
Else
strLocalHostInternal = ""
End If
Else
strLocalHostInternal = ""
End If
'get a 32 bits long IP
lngAddressInternal = ResolveIfHostnameSync(strLocalHostInternal, strIP, lngResult)
If lngResult <> 0 Then
Err.Raise sckInvalidArg, "CSocketMaster.BindInternal", "Invalid argument"
End If
'create a socket if there isn't one yet
If Not SocketExists Then Exit Function
Dim udtSockAddr As sockaddr_in
With udtSockAddr
.sin_addr = lngAddressInternal
.sin_family = AF_INET
.sin_port = api_htons(modSocketMaster.UnsignedToInteger(lngLocalPortInternal))
End With
'bind the socket
lngResult = api_bind(m_lngSocketHandle, udtSockAddr, LenB(udtSockAddr))
If lngResult = SOCKET_ERROR Then
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.BindInternal", GetErrorDescription(lngErrorCode)
Else
If lngLocalPortInternal <> 0 Then
If dodebug Then Debug.Print "OK Bind HOST: " & strLocalHostInternal & " PORT: " & lngLocalPortInternal
m_lngLocalPort = lngLocalPortInternal
Else
lngResult = GetLocalPort(m_lngSocketHandle)
If lngResult = SOCKET_ERROR Then
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.BindInternal", GetErrorDescription(lngErrorCode)
Else
If dodebug Then Debug.Print "OK Bind HOST: " & strLocalHostInternal & " PORT: " & lngResult
m_lngLocalPortBind = lngResult
End If
End If
BindInternal = True
End If
End Function
'Allocate some memory for HOSTEN structure and returns
'a pointer to this buffer if no error occurs.
'Returns 0 if it fails.
Private Function AllocateMemory() As Long
m_lngMemoryHandle = api_GlobalAlloc(GMEM_FIXED, MAXGETHOSTSTRUCT)
If m_lngMemoryHandle <> 0 Then
m_lngMemoryPointer = api_GlobalLock(m_lngMemoryHandle)
If m_lngMemoryPointer <> 0 Then
api_GlobalUnlock (m_lngMemoryHandle)
AllocateMemory = m_lngMemoryPointer
Else
api_GlobalFree (m_lngMemoryHandle)
AllocateMemory = m_lngMemoryPointer '0
End If
Else
AllocateMemory = m_lngMemoryHandle '0
End If
End Function
'Free memory allocated by AllocateMemory
Private Sub FreeMemory()
If m_lngMemoryHandle <> 0 Then
m_lngMemoryPointer = 0
api_GlobalFree m_lngMemoryHandle
m_lngMemoryHandle = 0
If dodebug Then Debug.Print "OK Freed resolution memory"
End If
End Sub
Private Function GetLocalHostName() As String
Dim strHostNameBuf As String * LOCAL_HOST_BUFF
Dim lngResult As Long
lngResult = api_gethostname(strHostNameBuf, LOCAL_HOST_BUFF)
If lngResult = SOCKET_ERROR Then
GetLocalHostName = vbNullString
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.GetLocalHostName", GetErrorDescription(lngErrorCode)
Else
GetLocalHostName = Left(strHostNameBuf, InStr(1, strHostNameBuf, vbNullChar) - 1)
End If
End Function
'Get local IP when the socket isn't connected yet
Private Function GetLocalIP() As String
Dim lngResult As Long
Dim lngPtrToIP As Long
Dim strLocalHost As String
Dim arrIpAddress(1 To 4) As Byte
Dim count As Integer
Dim udtHostent As HOSTENT
Dim strIpAddress As String
strLocalHost = GetLocalHostName
lngResult = api_gethostbyname(strLocalHost)
If lngResult = 0 Then
GetLocalIP = vbNullString
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Err.Raise lngErrorCode, "CSocketMaster.GetLocalIP", GetErrorDescription(lngErrorCode)
Else
api_CopyMemory udtHostent, ByVal lngResult, LenB(udtHostent)
api_CopyMemory lngPtrToIP, ByVal udtHostent.hAddrList, 4
api_CopyMemory arrIpAddress(1), ByVal lngPtrToIP, 4
For count = 1 To 4
strIpAddress = strIpAddress & arrIpAddress(count) & "."
Next
strIpAddress = Left$(strIpAddress, Len(strIpAddress) - 1)
GetLocalIP = strIpAddress
End If
End Function
'If Host is an IP doesn't resolve anything and returns a
'a 32 bits long IP.
'If Host isn't an IP then returns vbNull, tries to resolve it
'in asynchronous way.
Private Function ResolveIfHostname(ByVal Host As String) As Long
Dim lngAddress As Long
lngAddress = api_inet_addr(Host)
If lngAddress = INADDR_NONE Then 'if Host isn't an IP
ResolveIfHostname = vbNull
m_enmState = sckResolvingHost: If dodebug Then Debug.Print "STATE: sckResolvingHost"
If AllocateMemory Then
Dim lngAsynHandle As Long
lngAsynHandle = modSocketMaster.ResolveHost(Host, m_lngMemoryPointer, ObjPtr(Me))
If lngAsynHandle = 0 Then
FreeMemory
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"
Dim lngErrorCode As Long
lngErrorCode = Err.LastDllError
Dim blnCancelDisplay As Boolean
blnCancelDisplay = True
RaiseEvent Error(lngErrorCode, GetErrorDescription(lngErrorCode), 0, "CSocketMaster.ResolveIfHostname", "", 0, blnCancelDisplay)
If blnCancelDisplay = False Then MsgBox GetErrorDescription(lngErrorCode), vbOKOnly, "CSocketMaster.ResolveIfHostname"
Else
m_colWaitingResolutions.Add lngAsynHandle, "R" & lngAsynHandle
If dodebug Then Debug.Print "Resolving host " & Host; " with handle " & lngAsynHandle
End If
Else
m_enmState = sckError: If dodebug Then Debug.Print "STATE: sckError"