-
Notifications
You must be signed in to change notification settings - Fork 0
/
etherwake.cpp
4668 lines (4092 loc) · 161 KB
/
etherwake.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
// etherwake.cpp : définit le point d'entrée pour l'application console.
//
#include "stdafx.h"
#include "etherwake.h"
#include <Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
// #include <mstcpip.h>
#include <icmpapi.h>
#include "AutomaticVersionHeader.h"
#include "strstr.h"
#include "PrintRoutine.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#define LEN_TEXT_256 256
#define LEN_TEXT_1024 1024
#define LEN_TEXT_8192 8192
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
#ifndef _wsizeof
#define _wsizeof(x) (sizeof(x)/sizeof(WCHAR))
#endif
#define LEN_PATHNAME 280
#define NAMEANDWSIZE(x) x,sizeof(x)/sizeof(WCHAR)
//
// Process Creation
#define PROCESS_CREATION_FAILED 0xff
#define PROCESS_NOT_INVOKED 0xfe
//
const WCHAR *READ_BIN_MODE = L"rb";
const WCHAR *READ_MODE = L"r, ccs=UNICODE";
const WCHAR *WRITE_MODE = L"w";
const WCHAR *WRITE_BIN_MODE = L"wb";
const WCHAR *NULL_MAC_ADDR = L"00:00:00:00:00:00";
const WCHAR *BROADCAST_ADDR = L"FF:FF:FF:FF:FF:FF";
//
#define LEN_MAGIC_PACKET 102
static BYTE MagicWakePacket[LEN_MAGIC_PACKET];
#define LEN_MAC 6
static BYTE MacAddress [ LEN_MAC ];
static WCHAR MacAddressString [ LEN_MAC * 4 ];
static WCHAR IpV4StringW [ 64 ];
static WCHAR IpV6StringW [ 128 ];
static char IpV4StringA [ 64 ];
static char IpV6StringA [ 128 ];
static WCHAR ResolvedHostname [ 256 ];
static WCHAR NameServer [ LEN_TEXT_256 ] = L"";
//
//
PDNS_ADDR_ARRAY DNSArrayPtr = NULL;
DNS_ADDR_ARRAY DNSArray;
PIP4_ARRAY DNS4ArrayPtr = NULL;
IP4_ARRAY DNS4Array;
//
static WCHAR szHostName [ LEN_TEXT_256 ];
#define MAX_LENGTH 4096
static WCHAR AddressSearched [ MAX_LENGTH ] = L"";
static WCHAR MacFound [ MAX_LENGTH ] = L"";
static WCHAR szErrorText [ MAX_LENGTH ] = L"";
static WCHAR QueryType [ MAX_LENGTH ] = L"";
static WCHAR Subnet [ MAX_LENGTH ] = L"";
// Action
static bool DoAction = false;
static bool DoMac = false;
static bool DoArp = false;
static bool DoArp6 = false;
static bool DoAdapter = false;
static bool DoAdapter6 = false;
static bool DoList = false;
static bool DoWake = false;
static bool DoQuery = false;
// Flags
static bool IPv4Only = false;
static bool IPv6Only = false;
static bool NonZeroMac = false;
static bool IPUp = false;
static bool IPDown = false;
static bool ResolveMode = false;
static bool UseDns = false;
static bool DnsQueryExMode = false;
static bool PingMode = false;
static bool PingSubnetMode = false;
static bool PingListMode = false;
static bool IPMatchMac = false;
//
static WCHAR ModuleFileName [ MAX_LENGTH ] = L"";
static WCHAR InitFileName [ MAX_LENGTH ] = L"";
static WCHAR ArpFileName [ MAX_LENGTH ] = L"";
static WCHAR ExecuteCommand [ MAX_LENGTH ] = L"";
static WCHAR LocaleString [ MAX_LENGTH ] = L"";
static WCHAR PingFileName [ MAX_LENGTH ] = L"";
static WCHAR LineReadW [ MAX_LENGTH ] = L"";
static int FirstMacAddress = 1;
static DWORD PingTimeOut = 2;
//
struct IP_STRUCT
{
int binaryLength;
union
{
IN_ADDR inAddr;
IN6_ADDR inAddr6;
} binaryData;
};
//
// UP Address, Mac Address, hostname
#define LEN_IP_ARP 64
struct ArpItem
{
WCHAR IPAddress [ LEN_IP_ARP ];
IP_STRUCT IP;
WCHAR MacAddress [ LEN_IP_ARP ];
WCHAR HostName [ LEN_IP_ARP ];
int IPVersion;
};
#define MAX_ARP_LIST (8*1024)
int ArpListCount = 0;
bool ArpListUpdated = false;
ArpItem ArpList [ MAX_ARP_LIST ];
//
// Subnet
struct SubnetItem
{
WCHAR IPAddress [ LEN_IP_ARP ];
WCHAR IPMask [ LEN_IP_ARP ];
IN_ADDR IP;
IN_ADDR Mask;
};
#define MAX_SUBNET_LIST 64
int SubnetListCount = 0;
SubnetItem SubnetList [ MAX_SUBNET_LIST ];
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
#define USE_RTL_STRING_TO_IP4 0
#if USE_RTL_STRING_TO_IP4
typedef LONG (NTAPI *RtlIpv4StringToAddressWType)( _In_ PCWSTR S, _In_ BOOLEAN Strict, _Out_ LPCWSTR *Terminator, _Out_ struct in_addr *Addr );
RtlIpv4StringToAddressWType RtlIpv4StringToAddressW = NULL;
#endif
// DnsQueryEx
typedef DNS_STATUS ( WINAPI *DnsQueryExType )( _In_ PDNS_QUERY_REQUEST pQueryRequest, _Inout_ PDNS_QUERY_RESULT pQueryResults,
_Inout_opt_ PDNS_QUERY_CANCEL pCancelHandle );
DnsQueryExType RuntimeDnsQueryEx = NULL;
// RtlIpv4AddressToStringW
typedef PWSTR ( NTAPI *RtlIpv4AddressToStringWType ) ( _In_ const IN_ADDR *Addr, _Out_ WCHAR *S ) ;
RtlIpv4AddressToStringWType RtlIpv4AddressToStringW = NULL;
// RtlIpv6AddressToStringW
typedef PWSTR ( NTAPI *RtlIpv6AddressToStringWType ) ( _In_ const IN6_ADDR *Addr, _Out_ WCHAR *S ) ;
RtlIpv6AddressToStringWType RtlIpv6AddressToStringW = NULL;
// RtlIpv4AddressToStringExW
typedef LONG ( NTAPI *RtlIpv4AddressToStringExWType)( _In_ const IN_ADDR *Address, _In_ USHORT Port,
_Out_ LPWSTR AddressString, _Inout_ PULONG AddressStringLength );
RtlIpv4AddressToStringExWType RtlIpv4AddressToStringExW = NULL;
// RtlIpv6AddressToStringExW
typedef LONG ( NTAPI *RtlIpv6AddressToStringExWType)( _In_ const IN6_ADDR *Address, _In_ ULONG ScopeId, _In_ USHORT Port,
_Out_ LPWSTR AddressString, _Inout_ PULONG AddressStringLength );
RtlIpv6AddressToStringExWType RtlIpv6AddressToStringExW = NULL;
// Not Used
typedef LONG ( NTAPI *RtlIpv4StringToAddressExWType )( _In_ PCWSTR AddressString, _In_ BOOLEAN Strict,
_Out_ IN_ADDR *Address, _Out_ PUSHORT Port );
RtlIpv4StringToAddressExWType RtlIpv4StringToAddressExW = NULL;
typedef LONG ( NTAPI *RtlIpv6StringToAddressExWType )( _In_ PCWSTR AddressString, _Out_ IN6_ADDR *Address,
_Out_ PULONG ScopeId, _Out_ PUSHORT Port );
RtlIpv6StringToAddressExWType RtlIpv6StringToAddressExW = NULL;
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
void MacAddressToString ( BYTE macAddress [], ULONG length )
{
ZeroMemory ( MacAddressString, sizeof(MacAddressString) );
for ( ULONG i = 0; i < length; i++ )
{
swprintf(MacAddressString + wcslen(MacAddressString), _wsizeof(MacAddressString) - wcslen(MacAddressString), L"%02X", macAddress [ i ] );
if( i != length - 1 )
{
swprintf(MacAddressString + wcslen(MacAddressString), _wsizeof(MacAddressString) - wcslen(MacAddressString), L":" );
}
}
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
BOOL convertHexa1 ( WCHAR digit, BYTE *halfByte )
{
if ( digit >= L'0' && digit <= L'9' )
{
*halfByte = digit - '0';
}
else if ( digit >= L'A' && digit <= L'F' )
{
*halfByte = digit - 'A' + 10;
}
else if ( digit >= L'a' && digit <= L'f' )
{
*halfByte = digit - 'a' + 10;
}
else
{
return FALSE;
}
return TRUE;
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
BOOL convertHexa2 ( WCHAR *pText, BYTE *oneByte )
{
BYTE cHigh;
BYTE cLow;
BOOL bDone = convertHexa1 ( pText [ 0 ], &cHigh );
if ( ! bDone )
{
return FALSE;
}
bDone = convertHexa1 ( pText [ 1 ], &cLow );
if ( ! bDone )
{
return FALSE;
}
*oneByte = ( (WORD) cHigh ) << 4 | cLow;
return TRUE;
}
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
BOOL convertMAC ( WCHAR *pMacAddress )
{
int macIndex = 0;
for ( size_t i = 0; i < wcslen(pMacAddress); i++ )
{
BYTE oneByte;
BOOL bDone = convertHexa2 ( pMacAddress + i, &oneByte );
if ( ! bDone )
{
PrintStderrW ( L"Error : MAC Address error %s at '%c%c'\n", pMacAddress, pMacAddress [ i ], pMacAddress [ i + 1 ] );
return FALSE;
}
if ( macIndex >= LEN_MAC )
{
PrintStderrW ( L"Error : MAC Address too long\n");
return FALSE;
}
MacAddress [ macIndex ] = oneByte;
macIndex++;
i += 2;
if ( pMacAddress [ i ] != L'-' && pMacAddress [ i ] != L':' && pMacAddress [ i ] != L'\0' )
{
return FALSE;
}
}
if ( macIndex != 6 )
{
PrintStderrW ( L"Error : MAC Address too short %d\n", macIndex );
return FALSE;
}
return true;
}
//
//====================================================================================
// Get Numeric INetAddr
//====================================================================================
INT GetINetAddr4 ( WCHAR *pAddress, sockaddr_in *pSockaddr )
{
memset ( pSockaddr, 0, sizeof(sockaddr_in));
INT iSockaddr = sizeof(sockaddr_in);
INT iResult = WSAStringToAddress(
pAddress, // _In_ LPTSTR AddressString,
AF_INET, // _In_ INT AddressFamily,
NULL, // _In_opt_ LPWSAPROTOCOL_INFO lpProtocolInfo,
(LPSOCKADDR ) pSockaddr, // _Out_ LPSOCKADDR lpAddress,
&iSockaddr // _Inout_ LPINT lpAddressLength
);
return iResult;
}
//
//====================================================================================
// Get Numeric INetAddr
//====================================================================================
INT GetINetAddr6 ( WCHAR *pAddress, sockaddr_in6 *pSockaddr )
{
memset ( pSockaddr, 0, sizeof(sockaddr_in6));
INT iSockaddr = sizeof(sockaddr_in6);
INT iResult = WSAStringToAddress(
pAddress, // _In_ LPTSTR AddressString,
AF_INET6, // _In_ INT AddressFamily,
NULL, // _In_opt_ LPWSAPROTOCOL_INFO lpProtocolInfo,
(LPSOCKADDR ) pSockaddr, // _Out_ LPSOCKADDR lpAddress,
&iSockaddr // _Inout_ LPINT lpAddressLength
);
return iResult;
}
//
//====================================================================================
// Get Numeric INetAddr
//====================================================================================
INT GetINetAddr4 ( WCHAR *pAddress, IN_ADDR *pInAddr )
{
sockaddr_in sockAddr;
memset ( &sockAddr, 0, sizeof(sockAddr));
INT iSockaddr = sizeof(sockAddr);
INT iResult = WSAStringToAddress(
pAddress, // _In_ LPTSTR AddressString,
AF_INET, // _In_ INT AddressFamily,
NULL, // _In_opt_ LPWSAPROTOCOL_INFO lpProtocolInfo,
(LPSOCKADDR ) &sockAddr, // _Out_ LPSOCKADDR lpAddress,
&iSockaddr // _Inout_ LPINT lpAddressLength
);
*pInAddr = sockAddr.sin_addr;
return iResult;
}
//
//====================================================================================
// Get Numeric INetAddr
//====================================================================================
INT GetINetAddr6 ( WCHAR *pAddress, IN6_ADDR *pInAddr )
{
sockaddr_in6 sockAddr;
memset ( &sockAddr, 0, sizeof(sockAddr));
INT iSockaddr = sizeof(sockAddr);
INT iResult = WSAStringToAddress(
pAddress, // _In_ LPTSTR AddressString,
AF_INET6, // _In_ INT AddressFamily,
NULL, // _In_opt_ LPWSAPROTOCOL_INFO lpProtocolInfo,
(LPSOCKADDR ) &sockAddr, // _Out_ LPSOCKADDR lpAddress,
&iSockaddr // _Inout_ LPINT lpAddressLength
);
*pInAddr = sockAddr.sin6_addr;
return iResult;
}
//
//====================================================================================
// Return 0 if error
//====================================================================================
int PingAddress ( WCHAR *pIPAddress )
{
//
// Declare and initialize variables
// IPV4
if ( wcschr ( pIPAddress, L':' ) == NULL && wcschr ( pIPAddress, L'.' ) != NULL )
{
HANDLE hIcmpFile = NULL;
DWORD dwRetVal = 0;
char SendData[32] = "Data Buffer";
const DWORD ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);;
char ReplyBuffer [ ReplySize ];
// Validate the parameters
IN_ADDR inAddr;
ZeroMemory ( &inAddr, sizeof(inAddr));
int iRes = GetINetAddr4(pIPAddress, &inAddr);
if ( iRes != 0 || inAddr.S_un.S_addr == INADDR_NONE )
{
PrintStderr( L"Error on %s\n", pIPAddress);
return 0;
}
hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE)
{
PrintStderr( L"Unable to open handle. IcmpCreatefile returned error: %ld\n", GetLastError() );
return 0;
}
// Timeout 5 Milliseconds is enough for local
dwRetVal = IcmpSendEcho(hIcmpFile, inAddr.S_un.S_addr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, PingTimeOut);
if (dwRetVal != 0)
{
PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
struct in_addr ReplyAddr;
ReplyAddr.S_un.S_addr = pEchoReply->Address;
PrintVerbose ( L"\n> Sent icmp message to %s\n", pIPAddress);
if (dwRetVal > 1)
{
PrintVerbose ( L"< Received %ld icmp message responses - Information from the first response - ", dwRetVal);
}
else
{
PrintVerbose ( L"< Received %ld icmp message response - Information from this response - ", dwRetVal);
}
#if _MSC_VER < 1 // 1800
PrintVerboseA ( "Received from %s\n", inet_ntoa( ReplyAddr ) );
#else
WCHAR szAddress [ 64 ];
PCTSTR lpwStr = InetNtop(
AF_INET, // _In_ INT Family,
(PVOID) &ReplyAddr, // _In_ PVOID pAddr,
szAddress, // _Out_ PTSTR pStringBuf,
_wsizeof(szAddress) // _In_ size_t StringBufSize
);
PrintVerboseW ( L"Received from %s\n", szAddress );
#endif
PrintVerbose ( L"< Status = %ld - Roundtrip time = %ld milliseconds\n", pEchoReply->Status, pEchoReply->RoundTripTime);
}
else
{
PrintVerbose ( L"Call to IcmpSendEcho failed - IcmpSendEcho returned error: %ld\n", GetLastError() );
return 0;
}
}
// IPV6
else if ( wcschr ( pIPAddress, L':' ) != NULL )
{
HANDLE hIcmpFile = NULL;
DWORD dwRetVal = 0;
char SendData[32] = "Data Buffer";
const DWORD ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData);;
char ReplyBuffer [ ReplySize ];
ICMP6_ECHO_REPLY;
// Validate the parameters
sockaddr_in6 inAddrSource;
ZeroMemory ( &inAddrSource, sizeof(inAddrSource));
int iRes = GetINetAddr6(L"::", &inAddrSource);
if ( iRes != 0 )
{
PrintStderr( L"Error on %s\n", pIPAddress);
return 0;
}
sockaddr_in6 inAddrTarget;
ZeroMemory ( &inAddrTarget, sizeof(inAddrTarget));
iRes = GetINetAddr6(pIPAddress, &inAddrTarget);
if ( iRes != 0 )
{
PrintStderr( L"Error on %s\n", pIPAddress);
return 0;
}
hIcmpFile = Icmp6CreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE)
{
PrintStderr( L"Unable to open handle. IcmpCreatefile returned error: %ld\n", GetLastError() );
return 0;
}
// Timeout 5 Milliseconds is enough for local*
IP_OPTION_INFORMATION RequestOptions;
ZeroMemory ( &RequestOptions, sizeof(RequestOptions) );
//
dwRetVal =
Icmp6SendEcho2(
hIcmpFile, // _In_ HANDLE IcmpHandle,
NULL, // _In_opt_ HANDLE Event,
NULL, // _In_opt_ PIO_APC_ROUTINE ApcRoutine,
NULL, // _In_opt_ PVOID ApcContext,
&inAddrSource, // _In_ struct sockaddr_in6 *SourceAddress,
&inAddrTarget, // _In_ struct sockaddr_in6 *DestinationAddress,
SendData, // _In_ LPVOID RequestData,
sizeof(SendData), // _In_ WORD RequestSize,
NULL, // _In_opt_ PIP_OPTION_INFORMATION RequestOptions,
ReplyBuffer, // _Out_ LPVOID ReplyBuffer,
ReplySize, // _In_ DWORD ReplySize,
PingTimeOut // _In_ DWORD Timeout
);
if (dwRetVal != 0)
{
PICMPV6_ECHO_REPLY pEchoReply = (PICMPV6_ECHO_REPLY)ReplyBuffer;
PrintVerbose ( L"\n> Sent icmp message to %s\n", pIPAddress);
if (dwRetVal > 1)
{
PrintVerbose ( L"< Received %ld icmp message responses - Information from the first response - ", dwRetVal);
}
else
{
PrintVerbose ( L"< Received %ld icmp message response - Information from this response - ", dwRetVal);
}
SOCKADDR_IN6 sockAddrIn6;
ZeroMemory ( &sockAddrIn6, sizeof(sockAddrIn6) );
sockAddrIn6.sin6_family = AF_INET6;
sockAddrIn6.sin6_flowinfo = pEchoReply->Address.sin6_flowinfo;
sockAddrIn6.sin6_port = pEchoReply->Address.sin6_port;
sockAddrIn6.sin6_scope_id = pEchoReply->Address.sin6_scope_id;
memcpy ( sockAddrIn6.sin6_addr.u.Byte, pEchoReply->Address.sin6_addr, sizeof(sockAddrIn6.sin6_addr.u.Byte) );
//
WCHAR szAddress [ 64 ];
ZeroMemory ( szAddress, sizeof(szAddress) );
DWORD dwReturned = _wsizeof(szAddress);
INT iRes = WSAAddressToString(
(LPSOCKADDR)&sockAddrIn6, // LPSOCKADDR lpsaAddress,
sizeof(sockAddrIn6), // DWORD dwAddressLength,
NULL, // LPWSAPROTOCOL_INFOA lpProtocolInfo,
szAddress, // LPSTR lpszAddressString,
&dwReturned // LPDWORD lpdwAddressStringLength
);
if ( iRes != 0 )
{
int wsaError = WSAGetLastError();
PrintStderrW ( L"Error from 0x%x\n", wsaError );
}
PrintVerbose ( L"Received from %s\n", szAddress );
PrintVerbose ( L"< Status = %ld - Roundtrip time = %ld milliseconds\n", pEchoReply->Status, pEchoReply->RoundTripTime);
}
else
{
PrintVerbose ( L"Call to IcmpSendEcho failed - IcmpSendEcho returned error: %ld\n", GetLastError() );
return 0;
}
}
return 1;
}
//
//====================================================================================
//
//====================================================================================
bool IsInsideSubnet ( WCHAR *pIPAddress )
{
IN_ADDR inAddr;
ZeroMemory ( &inAddr, sizeof(inAddr) );
GetINetAddr4 ( pIPAddress, &inAddr );
for ( int i = 0; i < SubnetListCount; i++ )
{
ULONG ul = ( inAddr.S_un.S_addr ^ SubnetList [ i ].IP.S_un.S_addr );
ul = ul & SubnetList [ i ].Mask.S_un.S_addr;
if ( ul == 0 )
{
return true;
}
}
return false;
}
//
//====================================================================================
// Format Message
//====================================================================================
void FormatErrorMessage ( DWORD dwMessageId )
{
ZeroMemory ( szErrorText, sizeof(szErrorText) );
//
HRESULT hResult = HRESULT_FROM_WIN32(dwMessageId);
WCHAR *lpBuffer = NULL;
DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD dwResult = FormatMessage (
dwFlags, // DWORD dwFlags,
NULL, // LPCVOID lpSource,
dwMessageId, // DWORD dwMessageId,
NULL, // DWORD dwLanguageId,
(LPTSTR) &lpBuffer, // LPTSTR lpBuffer,
NULL, // DWORD nSize,
NULL // va_list* Arguments
);
if ( dwResult <= 0 )
{
DWORD dwOtherError = GetLastError ();
hResult = HRESULT_FROM_WIN32(dwOtherError);
}
if ( lpBuffer != NULL )
{
wcscpy_s ( szErrorText, _wsizeof (szErrorText), lpBuffer );
LocalFree ( lpBuffer );
}
}
//
////////////////////////////////////////////////////////////////////////
// Search Init File
////////////////////////////////////////////////////////////////////////
bool SearchInitFile ( WCHAR *pInitFileName, size_t iInitFileName )
{
WCHAR initName [ LEN_PATHNAME ];
WCHAR initPathName [ LEN_PATHNAME ];
WCHAR *pVariable = NULL;
size_t requiredSize = 0;
wcscpy_s ( NAMEANDWSIZE(initName), FindFileName ( pInitFileName ) );
//
// First If ini file is here.
if ( CheckPathExistW ( pInitFileName ) )
{
return true;
}
//
// Then Search Environnement
_wgetenv_s ( &requiredSize, NULL, 0, L"PATH" );
if ( requiredSize == 0 )
{
return false;
}
//
size_t iVariable = ( requiredSize + 1 ) * sizeof(WCHAR) + 1;
pVariable = ( WCHAR * ) malloc ( iVariable );
_wgetenv_s ( &requiredSize, pVariable, requiredSize + 1, L"PATH" );
// Treat Token for PATH
WCHAR strDelimit[] = L";";
WCHAR *strToken = NULL;
WCHAR *context = NULL;
//
// Treat Tokens
strToken = wcstok_s ( pVariable, strDelimit, &context);
while( strToken != NULL )
{
//
// Test Filename
wcscpy_s ( NAMEANDWSIZE(initPathName), strToken );
if ( ! EndsWithI ( initPathName, L"\\" ) )
{
wcscat_s ( NAMEANDWSIZE(initPathName), L"\\" );
}
wcscat_s ( NAMEANDWSIZE(initPathName), initName );
if ( CheckPathExistW ( initPathName ) )
{
wcscpy_s ( InitFileName, iInitFileName, initPathName );
free ( pVariable );
return true;
}
// Get next token:
strToken = wcstok_s( NULL, strDelimit, &context);
}
free ( pVariable );
return false;
}
//
////////////////////////////////////////////////////////////////////////
// Search Init File
////////////////////////////////////////////////////////////////////////
bool SearchArpFile ( WCHAR *pArpFileName, size_t iArpFileName )
{
WCHAR initName [ LEN_PATHNAME ];
WCHAR initPathName [ LEN_PATHNAME ];
WCHAR *pVariable = NULL;
size_t requiredSize = 0;
wcscpy_s ( NAMEANDWSIZE(initName), FindFileName ( pArpFileName ) );
//
// First If ini file is here.
if ( CheckPathExistW ( pArpFileName ) )
{
return true;
}
//
// Then Search Environnement
_wgetenv_s ( &requiredSize, NULL, 0, L"PATH" );
if ( requiredSize == 0 )
{
return false;
}
//
size_t iVariable = ( requiredSize + 1 ) * sizeof(WCHAR) + 1;
pVariable = ( WCHAR * ) malloc ( iVariable );
_wgetenv_s ( &requiredSize, pVariable, requiredSize + 1, L"PATH" );
// Treat Token for PATH
WCHAR strDelimit[] = L";";
WCHAR *strToken = NULL;
WCHAR *context = NULL;
//
// Treat Tokens
strToken = wcstok_s ( pVariable, strDelimit, &context);
while( strToken != NULL )
{
//
// Test Filename
wcscpy_s ( NAMEANDWSIZE(initPathName), strToken );
if ( ! EndsWithI ( initPathName, L"\\" ) )
{
wcscat_s ( NAMEANDWSIZE(initPathName), L"\\" );
}
wcscat_s ( NAMEANDWSIZE(initPathName), initName );
if ( CheckPathExistW ( initPathName ) )
{
wcscpy_s ( ArpFileName, iArpFileName, initPathName );
free ( pVariable );
return true;
}
// Get next token:
strToken = wcstok_s( NULL, strDelimit, &context);
}
free ( pVariable );
return false;
}
//
////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////
void GetModule ()
{
DWORD dwResult =
GetModuleFileName ( NULL, // __in_opt HMODULE hModule,
ModuleFileName, // __out LPTSTR lpFilename,
_wsizeof(ModuleFileName) // __in DWORD nSize
);
wcscpy_s ( NAMEANDWSIZE(InitFileName), ModuleFileName );
RemoveFileType ( InitFileName );
wcscat_s ( NAMEANDWSIZE(InitFileName), L".ini" );
wcscpy_s ( NAMEANDWSIZE(ArpFileName), ModuleFileName );
RemoveFileType ( ArpFileName );
wcscat_s ( NAMEANDWSIZE(ArpFileName), L".arp" );
//
// Search Init File and in Path
SearchInitFile ( NAMEANDWSIZE(InitFileName) );
SearchArpFile ( NAMEANDWSIZE(ArpFileName) );
PrintStdoutW ( L"Module File Name : %s\n", ModuleFileName );
PrintStdoutW ( L"Init File Name : %s\n", InitFileName );
PrintStdoutW ( L"Apr File Name : %s\n", ArpFileName );
}
//
//====================================================================================
//
//====================================================================================
void ReadArpFile ( )
{
memset ( ArpList, 0, sizeof(ArpList) );
ArpListCount = 0;
FILE *hArpFile = NULL;
OpenFileCcsW( &hArpFile, ArpFileName, L"r" );
if ( hArpFile == NULL )
{
return;
}
while ( ! feof ( hArpFile ) && ! ferror ( hArpFile ) )
{
WCHAR *pLine = fgetws ( LineReadW, _wsizeof(LineReadW), hArpFile );
if ( pLine )
{
RemoveCRLFW ( LineReadW );
WCHAR *pComma = wcschr ( pLine, L',' );
if ( pComma != NULL )
{
WCHAR *pMac = pComma + 1;
*pComma = '\0';
if ( ArpListCount < MAX_ARP_LIST )
{
WCHAR *pHostname = wcschr ( pMac, L',' );
if ( pHostname != NULL )
{
*pHostname = '\0';
pHostname++;
}
{
wcscpy_s ( ArpList [ ArpListCount ].IPAddress, _wsizeof(ArpList [ ArpListCount ].IPAddress), pLine );
wcscpy_s ( ArpList [ ArpListCount ].MacAddress, _wsizeof(ArpList [ ArpListCount ].MacAddress), pMac );
if ( pHostname != NULL )
{
wcscpy_s ( ArpList [ ArpListCount ].HostName, _wsizeof(ArpList [ ArpListCount ].HostName), pHostname );
}
RemoveLeadingByte ( ArpList [ ArpListCount ].IPAddress, L' ' );
RemoveTrailingByte ( ArpList [ ArpListCount ].IPAddress, L' ' );
// IP V4
if ( wcschr(ArpList [ ArpListCount ].IPAddress, L':') == 0 )
{
ArpList [ ArpListCount ].IP.binaryLength = sizeof(ArpList [ ArpListCount ].IP.binaryData.inAddr);
GetINetAddr4 ( ArpList [ ArpListCount ].IPAddress, &ArpList [ ArpListCount ].IP.binaryData.inAddr );
ArpList [ ArpListCount ].IPVersion = 4;
}
else
{
ArpList [ ArpListCount ].IP.binaryLength = sizeof(ArpList [ ArpListCount ].IP.binaryData.inAddr6);
GetINetAddr6 ( ArpList [ ArpListCount ].IPAddress, &ArpList [ ArpListCount ].IP.binaryData.inAddr6 );
ArpList [ ArpListCount ].IPVersion = 6;
}
RemoveLeadingByte ( ArpList [ ArpListCount ].MacAddress, L' ' );
RemoveTrailingByte ( ArpList [ ArpListCount ].MacAddress, L' ' );
RemoveLeadingByte ( ArpList [ ArpListCount ].HostName, L' ' );
RemoveTrailingByte ( ArpList [ ArpListCount ].HostName, L' ' );
ArpListCount++;
}
}
}
}
}
fclose ( hArpFile );
ArpListUpdated = false;
}
//
//====================================================================================
//
//====================================================================================
boolean convertIP ( WCHAR *pText, IP_STRUCT *pBinary )
{
//
if ( wcschr(pText, _TEXT(':') ) != NULL )
{
sockaddr_in6 in6Addr;
GetINetAddr6 ( pText, &in6Addr );
pBinary->binaryLength = sizeof(in6Addr.sin6_addr);
pBinary->binaryData.inAddr6 = in6Addr.sin6_addr;
return true;
}
//
// IPV4
else if ( wcschr(pText, _TEXT('.') ) != NULL )
{
sockaddr_in inAddr;
GetINetAddr4 ( pText, &inAddr );
pBinary->binaryLength = sizeof(inAddr.sin_addr);
pBinary->binaryData.inAddr = inAddr.sin_addr;
return true;
}
return false;
}
//
//====================================================================================
//
//====================================================================================
static int compareItem ( const void *pVoid1, const void *pVoid2 )
{
ArpItem *pOIX = (ArpItem *) pVoid1;
ArpItem *pOIY = (ArpItem *) pVoid2;
//
IP_STRUCT SIX;
IP_STRUCT SIY;
memset ( &SIX, 0, sizeof(SIX) );
memset ( &SIY, 0, sizeof(SIY) );
convertIP ( pOIX->IPAddress, &SIX );
convertIP ( pOIY->IPAddress, &SIY );
//
int iCmp = 0;
iCmp = memcmp ( &SIX, &SIY, sizeof(IP_STRUCT) );
// PrintDirectW ( L"%s versus %s = %d\n", pOIX->IPAddress, pOIY->IPAddress, iCmp );
return iCmp;
}
//
//====================================================================================
//
//====================================================================================
void WriteArpFile ( )
{
//
// Sort
qsort ( ArpList, ArpListCount, sizeof ( ArpItem ), compareItem );
//
FILE *hArpFile = NULL;
OpenFileCcsW( &hArpFile, ArpFileName, L"w" );
if ( hArpFile == NULL )
{
return;
}
for ( int i = 0; i < ArpListCount; i++ )
{
fwprintf ( hArpFile, L"%s,%s,%s\n", ArpList [ i ].IPAddress, ArpList [ i ].MacAddress, ArpList [ i ].HostName );
}
fclose ( hArpFile );
ArpListUpdated = false;
PrintDirect ( L"File %s has been updated\n", ArpFileName );
}
//
//====================================================================================
//
//====================================================================================
int SearchMacAddress ( WCHAR *pMac, int IPVersion )
{
for ( int i = 0; i < ArpListCount; i++ )
{
if ( wcscmp ( ArpList [ i ].MacAddress, pMac ) == 0 && ArpList [ i ].IPVersion == IPVersion )
{
return i;
}
}
return -1;
}
//
//====================================================================================