<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1820801</guid>
        <pubDate>Fri, 28 Dec 2007 19:27:09 +0000</pubDate>
        <title>Ping</title>
        <link>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1820801</link>
        <description><![CDATA[onyx: Вот уединенный модуль пинга. <br>
<br>
<span class="tag-color tag-color-named" data-value="gray" style="color: gray"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2007-12-28T22:39:12+03:00">28.12.07, 19:39</time></span></span><br>
Во ещё один пример. Надо использовать компонент IdIcmpClient. Этот включает метод Ping, который осуществляет запрос. Информация о посланном ping получена в свойство ReplyStatus компонента. Находим там число полученных байтов (BytesReceived), время в тысяче секунд (MsRoundTripTime), TTL пакета (TimeToLive), и т.д.. Вот в качестве примера функция, позволяющая определить ping, указываем IP или имя. Передаем также в параметре число отправлений, которое должны делать (чем больше число pings, тем результат будет точнее, но операция будет более медленнее выполняться), и  Double переменная, в которую поместим результат. Функция отсылает true, если все прошло успешно, false в случае провала:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">function TForm1.Ping(const AHost : string; const ATimes : integer;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;out AvgMS:Double) : Boolean;</div><div class="code_line">&nbsp;var</div><div class="code_line">&nbsp;&nbsp;R : array of Cardinal;</div><div class="code_line">&nbsp;&nbsp;i : integer;</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp;Result := True;</div><div class="code_line">&nbsp;&nbsp;AvgMS := 0;</div><div class="code_line">&nbsp;&nbsp;if ATimes&#62;0 then</div><div class="code_line">&nbsp;&nbsp; &nbsp;with TIdIcmpClient.Create(Self) do</div><div class="code_line">&nbsp;&nbsp; &nbsp;try</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Host := AHost;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ReceiveTimeout:=999; //TimeOut du ping</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;SetLength(R,ATimes);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{Pinguer le client}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for i:=0 to Pred(ATimes) do</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Ping();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Application.ProcessMessages; //ne bloque pas l&#39;application</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;R[i] := ReplyStatus.MsRoundTripTime;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;except</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Result := False;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Exit;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if ReplyStatus.ReplyStatusType&#60;&#62;rsEcho Then result := False; //pas d&#39;&#233;cho, on renvoi false.</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{Faire une moyenne}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for i:=Low(R) to High(R) do</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Application.ProcessMessages;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;AvgMS := AvgMS + R[i];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;AvgMS := AvgMS / i;</div><div class="code_line">&nbsp;&nbsp; &nbsp;finally</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Free;</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">end;</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script>]]></description>
        <author>onyx</author>
        <category>Интернет, сети, протоколы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818741</guid>
        <pubDate>Thu, 27 Dec 2007 09:15:11 +0000</pubDate>
        <title>Ping</title>
        <link>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818741</link>
        <description><![CDATA[onyx: <strong class='tag-b'>ICS - Internet Component Suite</strong> - богатый набор компонентов (TWSocket (TCP/IP, UDP - клиент, сервер), TsmtpCli (отправка почты), Tpop3Cli (получение почты), TftpCli (FTP клиент), TFtpSrv (FTP Сервер), ThttpCli (Веб клиент), THttpSrv (Веб сервер), Tping (он родимый и есть) и тд. и тп.). Скачать этот набор можно <a class='tag-url' href='http://www.overbyte.be/frame_index.html?redirTo=/products/ics.html' target='_blank'>здесь</a>.<br>
Для пинга необходим лишь TPing.<br>
Вот исходник-пример для пинга из архива с компонентом:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">unit PingTst1;</div><div class="code_line">&nbsp;</div><div class="code_line">interface</div><div class="code_line">&nbsp;</div><div class="code_line">uses</div><div class="code_line">&nbsp;&nbsp;Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,</div><div class="code_line">&nbsp;&nbsp;Ping, StdCtrls;</div><div class="code_line">&nbsp;</div><div class="code_line">type</div><div class="code_line">&nbsp;&nbsp;TPingTstForm = class(TForm)</div><div class="code_line">&nbsp;&nbsp; &nbsp;Ping1: TPing;</div><div class="code_line">&nbsp;&nbsp; &nbsp;Label1: TLabel;</div><div class="code_line">&nbsp;&nbsp; &nbsp;HostEdit: TEdit;</div><div class="code_line">&nbsp;&nbsp; &nbsp;PingButton: TButton;</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo: TMemo;</div><div class="code_line">&nbsp;&nbsp; &nbsp;CancelButton: TButton;</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure PingButtonClick(Sender: TObject);</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure Ping1Display(Sender: TObject; Icmp: TObject; Msg: String);</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure Ping1DnsLookupDone(Sender: TObject; Error: Word);</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure CancelButtonClick(Sender: TObject);</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure Ping1EchoRequest(Sender: TObject; Icmp: TObject);</div><div class="code_line">&nbsp;&nbsp; &nbsp;procedure Ping1EchoReply(Sender: TObject; Icmp: TObject; Error: Integer);</div><div class="code_line">&nbsp;&nbsp;private</div><div class="code_line">&nbsp;&nbsp; &nbsp;{ Dйclarations privйes }</div><div class="code_line">&nbsp;&nbsp;public</div><div class="code_line">&nbsp;&nbsp; &nbsp;{ Dйclarations publiques }</div><div class="code_line">&nbsp;&nbsp;end;</div><div class="code_line">&nbsp;</div><div class="code_line">var</div><div class="code_line">&nbsp;&nbsp;PingTstForm: TPingTstForm;</div><div class="code_line">&nbsp;</div><div class="code_line">implementation</div><div class="code_line">&nbsp;</div><div class="code_line">{$R *.DFM}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.PingButtonClick(Sender: TObject);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo.Clear;</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Resolving host &#39;&#39;&#39; + HostEdit.Text + &#39;&#39;&#39;&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;PingButton.Enabled &nbsp; := FALSE;</div><div class="code_line">&nbsp;&nbsp; &nbsp;CancelButton.Enabled := TRUE;</div><div class="code_line">&nbsp;&nbsp; &nbsp;Ping1.DnsLookup(HostEdit.Text);</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.Ping1DnsLookupDone(Sender: TObject; Error: Word);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;CancelButton.Enabled := FALSE;</div><div class="code_line">&nbsp;&nbsp; &nbsp;PingButton.Enabled &nbsp; := TRUE;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;if Error &#60;&#62; 0 then begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Unknown Host &#39;&#39;&#39; + HostEdit.Text + &#39;&#39;&#39;&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Exit;</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Host &#39;&#39;&#39; + HostEdit.Text + &#39;&#39;&#39; is &#39; + Ping1.DnsResult);</div><div class="code_line">&nbsp;&nbsp; &nbsp;Ping1.Address := Ping1.DnsResult;</div><div class="code_line">&nbsp;&nbsp; &nbsp;Ping1.Ping;</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.Ping1Display(Sender: TObject; Icmp: TObject; Msg: String);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo.Lines.Add(Msg);</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.CancelButtonClick(Sender: TObject);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;Ping1.CancelDnsLookup;</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.Ping1EchoRequest(Sender: TObject; Icmp: TObject);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Sending &#39; + IntToStr(Ping1.Size) + &#39; bytes to &#39; +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Ping1.HostName + &#39; (&#39; + Ping1.HostIP + &#39;)&#39;);</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">procedure TPingTstForm.Ping1EchoReply(Sender: TObject; Icmp: TObject; Error: Integer);</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;if Error = 0 then</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Cannot ping host (&#39; + Ping1.HostIP + &#39;) : &#39; +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Ping1.ErrorString)</div><div class="code_line">&nbsp;&nbsp; &nbsp;else</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;DisplayMemo.Lines.Add(&#39;Received &#39; + IntToStr(Ping1.Reply.DataSize) +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39; bytes from &#39; + Ping1.HostIP +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39; in &#39; + IntToStr(Ping1.Reply.RTT) + &#39; msecs&#39;);</div><div class="code_line">end;</div><div class="code_line">&nbsp;</div><div class="code_line">end.</div></ol></div></div></div></div>]]></description>
        <author>onyx</author>
        <category>Интернет, сети, протоколы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818639</guid>
        <pubDate>Thu, 27 Dec 2007 08:12:01 +0000</pubDate>
        <title>Ping</title>
        <link>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818639</link>
        <description><![CDATA[Rose: А чем так уж Indy не угодили? Или хотя бы ICS?  ;)]]></description>
        <author>Rose</author>
        <category>Интернет, сети, протоколы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818334</guid>
        <pubDate>Wed, 26 Dec 2007 20:46:39 +0000</pubDate>
        <title>Ping</title>
        <link>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818334</link>
        <description><![CDATA[onyx: Если нет желания связывается с Idy можно использовать библиотеку &quot;ICMP.DLL&quot;<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">uses</div><div class="code_line">&nbsp;&nbsp;WinSock;</div><div class="code_line">&nbsp;</div><div class="code_line">type</div><div class="code_line">&nbsp;&nbsp; &nbsp;ip_option_information = packed record &nbsp;// Информация заголовка IP (Наполнение</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// этой структуры и формат полей описан в RFC791.</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Ttl : byte; &nbsp; &nbsp; &nbsp; &nbsp; // Время жизни (используется traceroute-ом)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Tos : byte; &nbsp; &nbsp; &nbsp; &nbsp; // Тип обслуживания, обычно 0</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Flags : byte; &nbsp; &nbsp; &nbsp; // Флаги заголовка IP, обычно 0</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;OptionsSize : byte; &nbsp; &nbsp; // Размер данных в заголовке, обычно 0, максимум 40</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;OptionsData : Pointer; &nbsp;// Указатель на данные</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; icmp_echo_reply = packed record</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Address : u_long; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Адрес отвечающего</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Status : u_long; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // IP_STATUS (см. ниже)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;RTTime : u_long; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Время между эхо-запросом и эхо-ответом </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // в миллисекундах</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;DataSize : u_short; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Размер возвращенных данных</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Reserved : u_short; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Зарезервировано</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Data : Pointer; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Указатель на возвращенные данные</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Options : ip_option_information; // Информация из заголовка IP</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;PIPINFO = ^ip_option_information;</div><div class="code_line">&nbsp;&nbsp; &nbsp;PVOID = Pointer;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;function IcmpCreateFile() : THandle; stdcall; external &#39;ICMP.DLL&#39; name &#39;IcmpCreateFile&#39;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;function IcmpCloseHandle(IcmpHandle : THandle) : BOOL; stdcall; external &#39;ICMP.DLL&#39; &nbsp;name &#39;IcmpCloseHandle&#39;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;function IcmpSendEcho(</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IcmpHandle : THandle; &nbsp; &nbsp;// handle, возвращенный IcmpCreateFile()</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;DestAddress : u_long; &nbsp; &nbsp;// Адрес получателя (в сетевом порядке)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RequestData : PVOID; &nbsp; &nbsp; // Указатель на посылаемые данные</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RequestSize : Word; &nbsp; &nbsp; &nbsp;// Размер посылаемых данных</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RequestOptns : PIPINFO; &nbsp;// Указатель на посылаемую структуру </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ip_option_information (может быть nil)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ReplyBuffer : PVOID; &nbsp; &nbsp; // Указатель на буфер, содержащий ответы.</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ReplySize : DWORD; &nbsp; &nbsp; &nbsp; // Размер буфера ответов </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Timeout : DWORD &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Время ожидания ответа в миллисекундах</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) : DWORD; stdcall; external &#39;ICMP.DLL&#39; name &#39;IcmpSendEcho&#39;; </div><div class="code_line">&nbsp;</div><div class="code_line">procedure TForm1.Button1Click(Sender: TObject);</div><div class="code_line">var</div><div class="code_line">&nbsp;&nbsp; &nbsp;hIP : THandle;</div><div class="code_line">&nbsp;&nbsp; &nbsp;pingBuffer : array [0..31] of Char;</div><div class="code_line">&nbsp;&nbsp; &nbsp;pIpe : ^icmp_echo_reply;</div><div class="code_line">&nbsp;&nbsp; &nbsp;pHostEn : PHostEnt;</div><div class="code_line">&nbsp;&nbsp; &nbsp;wVersionRequested : WORD;</div><div class="code_line">&nbsp;&nbsp; &nbsp;lwsaData : WSAData;</div><div class="code_line">&nbsp;&nbsp; &nbsp;error : DWORD;</div><div class="code_line">&nbsp;&nbsp; &nbsp;destAddress : In_Addr;</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;// Создаем handle</div><div class="code_line">&nbsp;&nbsp; &nbsp;hIP := IcmpCreateFile(); </div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;GetMem( pIpe,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sizeof(icmp_echo_reply) + sizeof(pingBuffer));</div><div class="code_line">&nbsp;&nbsp; &nbsp;pIpe.Data := @pingBuffer;</div><div class="code_line">&nbsp;&nbsp; &nbsp;pIpe.DataSize := sizeof(pingBuffer);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;wVersionRequested := MakeWord(1,1);</div><div class="code_line">&nbsp;&nbsp; &nbsp;error := WSAStartup(wVersionRequested,lwsaData);</div><div class="code_line">&nbsp;&nbsp; &nbsp;if (error &#60;&#62; 0) then</div><div class="code_line">&nbsp;&nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.SetTextBuf(&#39;Error in call to &#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39;WSAStartup().&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.Lines.Add(&#39;Error code: &#39;+IntToStr(error));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Exit;</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;pHostEn := gethostbyname(&#39;172.16.10.1&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp;error := GetLastError();</div><div class="code_line">&nbsp;&nbsp; &nbsp;if (error &#60;&#62; 0) then</div><div class="code_line">&nbsp;&nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.SetTextBuf(&#39;Error in call to&#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39;gethostbyname().&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.Lines.Add(&#39;Error code: &#39;+IntToStr(error));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Exit;</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; destAddress := PInAddr(pHostEn^.h_addr_list^)^;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;// Посылаем ping-пакет</div><div class="code_line">&nbsp;&nbsp; &nbsp;Memo1.Lines.Add(&#39;Pinging &#39; +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;pHostEn^.h_name+&#39; [&#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;inet_ntoa(destAddress)+&#39;] &#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39; with &#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntToStr(sizeof(pingBuffer)) +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39; bytes of data:&#39;);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;IcmpSendEcho(hIP,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; destAddress.S_addr,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @pingBuffer,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sizeof(pingBuffer),</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Nil,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pIpe,</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sizeof(icmp_echo_reply) + sizeof(pingBuffer),</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5000);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;error := GetLastError();</div><div class="code_line">&nbsp;&nbsp; &nbsp;if (error &#60;&#62; 0) then</div><div class="code_line">&nbsp;&nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.SetTextBuf(&#39;Error in call to &#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&#39;IcmpSendEcho()&#39;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Memo1.Lines.Add(&#39;Error code: &#39;+IntToStr(error));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Exit;</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; // Смотрим некоторые из вернувшихся данных</div><div class="code_line">&nbsp;&nbsp; &nbsp;Memo1.Lines.Add(&#39;Reply from &#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntToStr(LoByte(LoWord(pIpe^.Address)))+&#39;.&#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntToStr(HiByte(LoWord(pIpe^.Address)))+&#39;.&#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntToStr(LoByte(HiWord(pIpe^.Address)))+&#39;.&#39;+</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IntToStr(HiByte(HiWord(pIpe^.Address))));</div><div class="code_line">&nbsp;&nbsp; &nbsp;Memo1.Lines.Add(&#39;Reply time: &#39;+IntToStr(pIpe.RTTime)+&#39; ms&#39;);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;IcmpCloseHandle(hIP);</div><div class="code_line">&nbsp;&nbsp; &nbsp;WSACleanup();</div><div class="code_line">&nbsp;&nbsp; &nbsp;FreeMem(pIpe);</div><div class="code_line">end;</div></ol></div></div></div></div> <br>
<br>
<span class="tag-color tag-color-named" data-value="gray" style="color: gray"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2007-12-26T20:51:56+00:00">26.12.07, 20:51</time></span></span><br>
А вот таким незаурядным кодом в одну строку можно вывести в командной строке результат пинга адреса:<br>
WinExec(pchar(&#39;ping.exe sources.ru&#39;), sw_show);]]></description>
        <author>onyx</author>
        <category>Интернет, сети, протоколы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818213</guid>
        <pubDate>Wed, 26 Dec 2007 19:09:38 +0000</pubDate>
        <title>Ping</title>
        <link>https://forum.sources.ru/index.php?showtopic=217145&amp;view=findpost&amp;p=1818213</link>
        <description><![CDATA[onyx: <span class="tag-color tag-color-named" data-value="purple" style="color: purple"><span class='tag-size' data-value='14' style='font-size:14pt;'>Ping средствами Delphi</span></span><br>
<br>
<em class='tag-i'>Ping</em> — это служебная компьютерная программа, предназначенная для проверки соединений в сетях на основе <em class='tag-i'>TCP/IP</em>.<br>
<br>
Она отправляет запросы <em class='tag-i'>Echo-Request</em> протокола <em class='tag-i'>ICMP </em>указанному узлу сети и фиксирует поступающие ответы <em class='tag-i'>(ICMP Echo-Reply)</em>. Время между отправкой запроса и получением ответа позволяет определять двусторонние задержки <em class='tag-i'>(RTT)</em> по маршруту и частоту потери пакетов, то есть косвенно определять загруженности каналов передачи данных и промежуточных устройств.<br>
<br>
Также пингом называется время, затраченное на передачу пакета информации в компьютерных сетях от клиента к серверу и обратно от сервера к клиенту, оно измеряется в миллисекундах. Время пинга связано со скоростью соединения и загруженностью каналов на всём протяжении от клиента к серверу.<br>
<br>
Полное отсутствие <em class='tag-i'>ICMP</em>-ответов может также означать, что удалённый узел (или какой-либо из промежуточных маршрутизаторов) блокирует <em class='tag-i'>ICMP Echo-Reply</em> или игнорирует <em class='tag-i'>ICMP Echo-Request</em>.<br>
<br>
А теперь конкретно на примерах.<br>
<br>
В основу одного из самого простого способа можно положить стандартную утилиту командной строки <em class='tag-i'>ping.exe</em>, входящую в состав Windows. <br>
Команда Ping лежит в основе диагностики сетей TCP/IP. Например, чтобы быстро получить значения параметров конфигурации TCP/IP на своем компьютере в командной строке, следует набрать:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">C:\&#62;ping 127.0.0.1</div></ol></div></div></div></div><br>
Результатом данной команды будет:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">Обмен пакетами с 127.0.0.1 по 32 байт:</div><div class="code_line">Ответ от 127.0.0.1: число байт=32 время&#60;1мс TTL=128</div><div class="code_line">Ответ от 127.0.0.1: число байт=32 время&#60;1мс TTL=128</div><div class="code_line">Ответ от 127.0.0.1: число байт=32 время&#60;1мс TTL=128</div><div class="code_line">Ответ от 127.0.0.1: число байт=32 время&#60;1мс TTL=128</div><div class="code_line">Статистика Ping для 127.0.0.1:</div><div class="code_line">Пакетов: отправлено = 4, получено = 4, потеряно = 0 (0% потерь),</div><div class="code_line">Приблизительное время приема-передачи в мс:</div><div class="code_line">Минимальное = 0мсек, Максимальное = 0 мсек, Среднее = 0 мсек</div></ol></div></div></div></div><br>
Более подробное описание этой утилиты есть в справке Windows, не будем на этом зацикливаться.<br>
Так вот, принцип работы delphi-приложения, основанного на данной утилите, будет не сложным. Будет необходимым передать утилите необходимые параметры, а именно IP-адрес, и принять результат работы. Не сложно, правда? <br>
Вот небольшая процедурка:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">procedure Ping(IP: String; OutMemo:TMemo);</div><div class="code_line">const BUFSIZE = 2000;</div><div class="code_line">var SecAttr &nbsp; &nbsp;: TSecurityAttributes;</div><div class="code_line">&nbsp;&nbsp; hReadPipe,</div><div class="code_line">&nbsp;&nbsp; hWritePipe : THandle;</div><div class="code_line">&nbsp;&nbsp; StartupInfo: TStartUpInfo;</div><div class="code_line">&nbsp;&nbsp; ProcessInfo: TProcessInformation;</div><div class="code_line">&nbsp;&nbsp; Buffer &nbsp; &nbsp; : Pchar;</div><div class="code_line">&nbsp;&nbsp; WaitReason,</div><div class="code_line">&nbsp;&nbsp; BytesRead &nbsp;: DWord;</div><div class="code_line">begin</div><div class="code_line">with SecAttr do</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp;nlength &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;:= SizeOf(TSecurityAttributes);</div><div class="code_line">&nbsp;&nbsp;binherithandle &nbsp; &nbsp; &nbsp; := true;</div><div class="code_line">&nbsp;&nbsp;lpsecuritydescriptor := nil;</div><div class="code_line">end;</div><div class="code_line">if Createpipe (hReadPipe, hWritePipe, @SecAttr, 0) then</div><div class="code_line">begin</div><div class="code_line">&nbsp;&nbsp;Buffer &nbsp;:= AllocMem(BUFSIZE + 1);</div><div class="code_line">&nbsp;&nbsp;FillChar(StartupInfo, Sizeof(StartupInfo), #0);</div><div class="code_line">&nbsp;&nbsp;StartupInfo.cb &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;:= SizeOf(StartupInfo);</div><div class="code_line">&nbsp;&nbsp;StartupInfo.hStdOutput &nbsp;:= hWritePipe;</div><div class="code_line">&nbsp;&nbsp;StartupInfo.hStdInput &nbsp; := hReadPipe;</div><div class="code_line">&nbsp;&nbsp;StartupInfo.dwFlags &nbsp; &nbsp; := STARTF_USESTDHANDLES +</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; STARTF_USESHOWWINDOW;</div><div class="code_line">&nbsp;&nbsp;StartupInfo.wShowWindow := SW_HIDE;</div><div class="code_line">&nbsp;&nbsp;if CreateProcess(nil,</div><div class="code_line">&nbsp;&nbsp; &nbsp; PChar(&#39;ping.exe &#39;+IP),</div><div class="code_line">&nbsp;&nbsp; &nbsp; @SecAttr,</div><div class="code_line">&nbsp;&nbsp; &nbsp; @SecAttr,</div><div class="code_line">&nbsp;&nbsp; &nbsp; true,</div><div class="code_line">&nbsp;&nbsp; &nbsp; NORMAL_PRIORITY_CLASS,</div><div class="code_line">&nbsp;&nbsp; &nbsp; nil,</div><div class="code_line">&nbsp;&nbsp; &nbsp; nil,</div><div class="code_line">&nbsp;&nbsp; &nbsp; StartupInfo,</div><div class="code_line">&nbsp;&nbsp; &nbsp; ProcessInfo) then</div><div class="code_line">&nbsp;&nbsp; &nbsp;begin</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;repeat</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;WaitReason := WaitForSingleObject( ProcessInfo.hProcess,100);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Application.ProcessMessages;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;until (WaitReason &#60;&#62; WAIT_TIMEOUT);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;Repeat</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;BytesRead := 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ReadFile(hReadPipe, Buffer[0], BUFSIZE, BytesRead, nil);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Buffer[BytesRead]:= #0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;OemToAnsi(Buffer,Buffer);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;OutMemo.Text := OutMemo.text + String(Buffer);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;until (BytesRead &#60; BUFSIZE);</div><div class="code_line">&nbsp;&nbsp; &nbsp;end;</div><div class="code_line">&nbsp;&nbsp;FreeMem(Buffer);</div><div class="code_line">&nbsp;&nbsp;CloseHandle(ProcessInfo.hProcess);</div><div class="code_line">&nbsp;&nbsp;CloseHandle(ProcessInfo.hThread);</div><div class="code_line">&nbsp;&nbsp;CloseHandle(hReadPipe);</div><div class="code_line">&nbsp;&nbsp;CloseHandle(hWritePipe);</div><div class="code_line">end;</div><div class="code_line">end;</div></ol></div></div></div></div><br>
Процедура отправляет IP адрес и возвращает в TMemo результат работы.<br>
Вот пример использования:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">Ping(&#39;127.0.0.1&#39;, Memo1);</div></ol></div></div></div></div><br>
<br>
При подготовке данной статьи были использованы следующие материалы:<br>
<a class='tag-url' href='http://ru.wikipedia.org/wiki/Ping' target='_blank'>Общее представление о пинге (Википедия)</a><br>
<a class='tag-url' href='http://www.drkb.ru/' target='_blank'>Процедура принятия результатов работы консольного приложения (DRKB)</a> <br>
<br>
<span class="tag-color tag-color-named" data-value="gray" style="color: gray"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2007-12-26T19:20:02+00:00">26.12.07, 19:20</time></span></span><br>
Пинг можно реализовать компонентом IdIcmpClient со страницы IndyClient, используя его метод ping и считывая потом ReplyStatus. <br>
<br>
Пример кода:<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">IdIcmpClient1.Ping;</div><div class="code_line">Memo1.Lines.Add(IntToStr(IdIcmpClient1.ReplyStatus.TimeToLive));</div></ol></div></div></div></div>]]></description>
        <author>onyx</author>
        <category>Интернет, сети, протоколы</category>
      </item>
	
      </channel>
      </rss>
	