Delphi-Projects
123 строки · 2.7 Кб
1unit PingUnit;
2
3interface
4uses
5Windows, SysUtils, Classes, LogUnit;
6
7type
8TSunB = packed record
9s_b1, s_b2, s_b3, s_b4: byte;
10end;
11
12TSunW = packed record
13s_w1, s_w2: word;
14end;
15
16PIPAddr = ^TIPAddr;
17TIPAddr = record
18case integer of
190: (S_un_b: TSunB);
201: (S_un_w: TSunW);
212: (S_addr: longword);
22end;
23
24IPAddr = TIPAddr;
25
26function IcmpCreateFile : THandle; stdcall; external 'icmp.dll';
27function IcmpCloseHandle (icmpHandle : THandle) : boolean; stdcall; external 'icmp.dll';
28function IcmpSendEcho (IcmpHandle : THandle; DestinationAddress : IPAddr;
29RequestData : Pointer; RequestSize : Smallint;
30RequestOptions : pointer;
31ReplyBuffer : Pointer;
32ReplySize : DWORD;
33Timeout : DWORD) : DWORD; stdcall; external 'icmp.dll';
34
35
36function Ping(InetAddress : string) : boolean;
37
38procedure TranslateStringToTInAddr(AIP: string; var AInAddr);
39
40implementation
41
42uses
43WinSock;
44
45function Fetch(var AInput: string; const ADelim: string = ' '; const ADelete: Boolean = true)
46: string;
47var
48iPos: Integer;
49begin
50if ADelim = #0 then begin
51// AnsiPos does not work with #0
52iPos := Pos(ADelim, AInput);
53end else begin
54iPos := Pos(ADelim, AInput);
55end;
56if iPos = 0 then begin
57Result := AInput;
58if ADelete then begin
59AInput := '';
60end;
61end else begin
62result := Copy(AInput, 1, iPos - 1);
63if ADelete then begin
64Delete(AInput, 1, iPos + Length(ADelim) - 1);
65end;
66end;
67end;
68
69procedure TranslateStringToTInAddr(AIP: string; var AInAddr);
70var
71phe: PHostEnt;
72pac: PChar;
73GInitData: TWSAData;
74begin
75WSAStartup($101, GInitData);
76try
77phe := GetHostByName(PChar(AIP));
78if Assigned(phe) then
79begin
80pac := phe^.h_addr_list^;
81if Assigned(pac) then
82begin
83with TIPAddr(AInAddr).S_un_b do begin
84s_b1 := Byte(pac[0]);
85s_b2 := Byte(pac[1]);
86s_b3 := Byte(pac[2]);
87s_b4 := Byte(pac[3]);
88end;
89end
90else
91begin
92raise Exception.Create('Error getting IP from HostName');
93end;
94end
95else
96begin
97raise Exception.Create('Error getting HostName');
98end;
99except
100FillChar(AInAddr, SizeOf(AInAddr), #0);
101end;
102WSACleanup;
103end;
104
105function Ping(InetAddress : string) : boolean;
106var
107Handle : THandle;
108InAddr : IPAddr;
109DW : DWORD;
110rep : array[1..128] of byte;
111begin
112Result := false;
113Handle := IcmpCreateFile;
114if Handle = INVALID_HANDLE_VALUE then
115Exit;
116TranslateStringToTInAddr(InetAddress, InAddr);
117DW := IcmpSendEcho(Handle, InAddr, nil, 0, nil, @rep, 128, 0);
118Log(InetAddress + ' IcmpSendEcho: ' + IntToStr(DW));
119Result := (DW <> 0);
120IcmpCloseHandle(Handle);
121end;
122
123end.
124