C++ Builder CE code fragment

TIdIcmpClientを使ってネットワークの”疎通”を調べる件

プロトコルの流れで一度紹介しようと思っていたところ、

“tidicmpclient timeout delphi example”というようないかにもなワードでBing君で検索したら、案の定Copilot君がお出ましました。その内容も面白いのですが、今回はその下の何度かここでも書いてるRemy氏のご託宣が出てきたので、そこから紹介します。

Remy氏TidIcmpClinetのReplyを解釈しているコードは、

procedure DoPing;
begin
  IdIcmpClient1.ReceiveTimeout := 200;
  IdIcmpClient1.Host := '8.8.8.8';
  IdIcmpClient1.Ping;
  if IdIcmpClient1.ReplyStatus.ReplyStatusType = rsEcho then
  begin
    // got some data, connection is up
  end
  else if IdIcmpClient1.ReplyStatus.ReplyStatusType = rsTimeout then
  begin
    // have a timeout, link is down
  end
  else
  begin
    // some other response, do something else...
  end;
end;

です。ほぼ間違いないですが、rsTimeoutrsTimeOutの間違いなので、そこを修正して、側をかぶせたC++ Builderのプログラムのコード部分は、

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TPing *Ping;
//---------------------------------------------------------------------------
__fastcall TPing::TPing(TComponent* Owner)
	: TForm(Owner)
{

}
//---------------------------------------------------------------------------

/*
procedure DoPing;
begin
  IdIcmpClient1.ReceiveTimeout := 200;
  IdIcmpClient1.Host := '8.8.8.8';
  IdIcmpClient1.Ping;
  if IdIcmpClient1.ReplyStatus.ReplyStatusType = rsEcho then
  begin
    // got some data, connection is up
  end
  else if IdIcmpClient1.ReplyStatus.ReplyStatusType = rsTimeout then
  begin
    // have a timeout, link is down
  end
  else
  begin
    // some other response, do something else...
  end;
end;

*/

void __fastcall TPing::Button1Click(TObject *Sender)
{
 	IdIcmpClient1->ReceiveTimeout = 200;
	IdIcmpClient1->Host = Edit1->Text;
	IdIcmpClient1->Ping();

	if( IdIcmpClient1->ReplyStatus->ReplyStatusType == rsEcho )
		Label1->Caption = "live";
	else if( IdIcmpClient1->ReplyStatus->ReplyStatusType == rsTimeOut )
		Label1->Caption = "Time out";
	else
		Label1->Caption = "Down";

}
//---------------------------------------------------------------------------

/*
type
  TReplyStatusTypes = (rsEcho,
    rsError, rsTimeOut, rsErrorUnreachable,
    rsErrorTTLExceeded,rsErrorPacketTooBig,
    rsErrorParameter,
    rsErrorDatagramConversion,
    rsErrorSecurityFailure,
    rsSourceQuench,
    rsRedirect,
    rsTimeStamp,
    rsInfoRequest,
    rsAddressMaskRequest,
    rsTraceRoute,
    rsMobileHostReg,
    rsMobileHostRedir,
    rsIPv6WhereAreYou,
    rsIPv6IAmHere,
	rsSKIP);

*/

これになりますが、例によって筆者のやり方でDelphiのコードをコメントとして入れておいて、それを見ながら書いてます。あー、FormにはもちろんTIdIcmpClinetのコンポーネントを置いてくださいね。さらにping先のホスト名を入れるTEditと、結果を表示するTLabelとPingするTButtonが必要です。

こんな感じです。IPアドレス8.8.8.8を見てどこのサイトかが分かる方は、DNSがらみで苦労したことがある方だと思われますね。関数化した方が便利ですが、それは次号で。

コメント