用delphi写的ping程序,但如何判断ping通或ping不通?

Michaelyfj 2001-07-09 09:21:53
用delphi写的ping程序,但如何判断ping通或ping不通?
...全文
234 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Michaelyfj 2001-07-10
  • 打赏
  • 举报
回复
to skimwater(掠水惊鸿):
正合吾意~!
to xiaozi(小子):
非常不错,没有功劳也有苦劳!
给分...
xiaozi 2001-07-09
  • 打赏
  • 举报
回复
我给一个完整的例子你,是用BCB的。

//ping.h
//---------------------------------------------------------------------------
#ifndef PingH
#define PingH
//---------------------------------------------------------------------------
#include <vcl.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
//---------------------------------------------------------------------------

#pragma pack(1)

#define ICMP_ECHOREPLY 0
#define ICMP_ECHOREQ 8

// IP Header -- RFC 791
typedef struct tagIPHDR
{
u_char VIHL; // Version and IHL
u_char TOS; // Type Of Service
short TotLen; // Total Length
short ID; // Identification
short FlagOff; // Flags and Fragment Offset
u_char TTL; // Time To Live
u_char Protocol; // Protocol
u_short Checksum; // Checksum
struct in_addr iaSrc; // Internet Address - Source
struct in_addr iaDst; // Internet Address - Destination
}IPHDR, *PIPHDR;


// ICMP Header - RFC 792
typedef struct tagICMPHDR
{
u_char Type; // Type
u_char Code; // Code
u_short Checksum; // Checksum
u_short ID; // Identification
u_short Seq; // Sequence
char Data; // Data
}ICMPHDR, *PICMPHDR;


#define REQ_DATASIZE 32 // Echo Request Data size

// ICMP Echo Request
typedef struct tagECHOREQUEST
{
ICMPHDR icmpHdr;
DWORD dwTime;
char cData[REQ_DATASIZE];
}ECHOREQUEST, *PECHOREQUEST;


// ICMP Echo Reply
typedef struct tagECHOREPLY
{
IPHDR ipHdr;
ECHOREQUEST echoRequest;
char cFiller[256];
}ECHOREPLY, *PECHOREPLY;
#pragma pack()

//--------------------------------------------------------------------------------
#define INIT_SUCCESS 0
#define TP_ERR_INIT -1
#define ERR_VERSION_NOT_SUPPORT -2
#define TP_ERR_INIT 0x1001

class TPing
{
private:
HWND m_hwnd;
TListBox * m_pReportListBox;
public:
__fastcall TPing(HWND hwnd,TListBox * pReportLst);
DWORD __fastcall Init();
void __fastcall UnLoad();
void __fastcall UserPing(LPCSTR pstrHost);
void __fastcall ReportError(LPCSTR pstrFrom);
int __fastcall WaitForEchoReply(SOCKET s);
u_short __fastcall in_cksum(u_short *addr, int len);

// ICMP Echo Request/Reply functions
int __fastcall SendEchoRequest(SOCKET, LPSOCKADDR_IN);
DWORD __fastcall RecvEchoReply(SOCKET, LPSOCKADDR_IN, u_char *);
};
//--------------------------------------------------------------------------------
#endif

//ping.cpp
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Ping.h"

//--------------------------------------------------------------------------------
//
// PING.C -- Ping program using ICMP and RAW Sockets
//
__fastcall TPing::TPing(HWND hwnd,TListBox * pReportLst)
{
m_hwnd=hwnd;
m_pReportListBox=pReportLst;
}
//--------------------------------------------------------------------------------
void __fastcall TPing::UnLoad()
{
WSACleanup();
}
//--------------------------------------------------------------------------------
DWORD __fastcall TPing::Init()
{
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(1,1);
int nRet = WSAStartup(wVersionRequested, &wsaData);
if(nRet != 0)
return TP_ERR_INIT;
// Check version
if(wsaData.wVersion != wVersionRequested)
return ERR_VERSION_NOT_SUPPORT;
}
//--------------------------------------------------------------------------------

// Ping()
// Calls SendEchoRequest() and
// RecvEchoReply() and prints results
void __fastcall TPing::UserPing(LPCSTR pstrHost)
{
SOCKET rawSocket;
LPHOSTENT lpHost;
struct sockaddr_in saDest;
struct sockaddr_in saSrc;
DWORD dwTimeSent;
DWORD dwElapsed;
u_char cTTL;
int nLoop;
int nRet;
char buf[256];

// Create a Raw socket
rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if(rawSocket == SOCKET_ERROR)
{
ReportError("socket()");
return;
}

// Lookup host
lpHost = gethostbyname(pstrHost);
if(lpHost == NULL)
{
sprintf(buf,"\nHost not found: %s\n", pstrHost);
m_pReportListBox->Items->Add(buf);
return;
}

// Setup destination socket address
saDest.sin_addr.s_addr = *((u_long FAR *) (lpHost->h_addr));
saDest.sin_family = AF_INET;
saDest.sin_port = 0;

// Tell the user what we're doing

sprintf(buf,"\nPinging %s [%s] with %d bytes of data:\n",
pstrHost,
inet_ntoa(saDest.sin_addr),
REQ_DATASIZE);
m_pReportListBox->Items->Add(buf);

// Ping multiple times
for(nLoop = 0; nLoop < 4; nLoop++)
{
// Send ICMP echo request
SendEchoRequest(rawSocket, &saDest);
// Use select() to wait for data to be received
nRet = WaitForEchoReply(rawSocket);
if (nRet == SOCKET_ERROR)
{
ReportError("select()");
break;
}
if(!nRet)
{
sprintf(buf,"TimeOut");
m_pReportListBox->Items->Add(buf);
break;
}

// Receive reply
dwTimeSent = RecvEchoReply(rawSocket, &saSrc, &cTTL);

// Calculate elapsed time
dwElapsed = GetTickCount() - dwTimeSent;
sprintf(buf,"Reply from: %s: bytes=%d time=%ldms TTL=%d",
inet_ntoa(saSrc.sin_addr),
REQ_DATASIZE,
dwElapsed,
cTTL);
m_pReportListBox->Items->Add(buf);
}
nRet = closesocket(rawSocket);
if (nRet == SOCKET_ERROR)
ReportError("closesocket()");
}

// SendEchoRequest()
// Fill in echo request header
// and send to destination
int __fastcall TPing::SendEchoRequest(SOCKET s,LPSOCKADDR_IN lpstToAddr)
{
static ECHOREQUEST echoReq;
static nId = 1;
static nSeq = 1;
int nRet;

// Fill in echo request
echoReq.icmpHdr.Type = ICMP_ECHOREQ;
echoReq.icmpHdr.Code = 0;
echoReq.icmpHdr.Checksum = 0;
echoReq.icmpHdr.ID = nId++;
echoReq.icmpHdr.Seq = nSeq++;

// Fill in some data to send
for(nRet = 0; nRet < REQ_DATASIZE; nRet++)
echoReq.cData[nRet] = ' '+nRet;

// Save tick count when sent
echoReq.dwTime = GetTickCount();

// Put data in packet and compute checksum
echoReq.icmpHdr.Checksum = in_cksum((u_short *)&echoReq, sizeof(ECHOREQUEST));

// Send the echo request
nRet = sendto(s, // socket
(LPSTR)&echoReq, // buffer
sizeof(ECHOREQUEST),
0, // flags
(LPSOCKADDR)lpstToAddr, // destination
sizeof(SOCKADDR_IN)); // address length

if (nRet == SOCKET_ERROR)
ReportError("sendto()");
return (nRet);
}


// RecvEchoReply()
// Receive incoming data
// and parse out fields
DWORD __fastcall TPing::RecvEchoReply(SOCKET s, LPSOCKADDR_IN lpsaFrom, u_char *pTTL)
{
ECHOREPLY echoReply;
int nRet;
int nAddrLen = sizeof(struct sockaddr_in);

// Receive the echo reply
nRet = recvfrom(s, // socket
(LPSTR)&echoReply, // buffer
sizeof(ECHOREPLY), // size of buffer
0, // flags
(LPSOCKADDR)lpsaFrom, // From address
&nAddrLen); // pointer to address len

// Check return value
if (nRet == SOCKET_ERROR)
ReportError("recvfrom()");

// return time sent and IP TTL
*pTTL = echoReply.ipHdr.TTL;
return(echoReply.echoRequest.dwTime);
}

// What happened?
void __fastcall TPing::ReportError(LPCSTR pWhere)
{
char Buf[256];
sprintf(Buf,"\n%s error: %d\n",pWhere,WSAGetLastError());
m_pReportListBox->Items->Add(Buf);
}


// WaitForEchoReply()
// Use select() to determine when
// data is waiting to be read
int __fastcall TPing::WaitForEchoReply(SOCKET s)
{
struct timeval Timeout;
fd_set readfds;

readfds.fd_count = 1;
readfds.fd_array[0] = s;
Timeout.tv_sec = 5;
Timeout.tv_usec = 0;

return(select(1, &readfds, NULL, NULL, &Timeout));
}


//
// Mike Muuss' in_cksum() function
// and his comments from the original
// ping program
//
// * Author -
// * Mike Muuss
// * U. S. Army Ballistic Research Laboratory
// * December, 1983

//
// I N _ C K S U M
//
// Checksum routine for Internet Protocol family headers (C Version)
//
//
u_short __fastcall TPing::in_cksum(u_short *addr, int len)
{
register int nleft = len;
register u_short *w = addr;
register u_short answer;
register int sum = 0;

//
// Our algorithm is simple, using a 32 bit accumulator (sum),
// we add sequential 16 bit words to it, and at the end, fold
// back all the carry bits from the top 16 bits into the lower
// 16 bits.
//
while( nleft > 1 )
{
sum += *w++;
nleft -= 2;
}

// mop up an odd byte, if necessary
if( nleft == 1 )
{
u_short u = 0;
*(u_char *)(&u) = *(u_char *)w ;
sum += u;
}

//
// add back carry outs from top 16 bits to low 16 bits
//
sum = (sum >> 16) + (sum & 0xffff); // add hi 16 to low 16
sum += (sum >> 16); // add carry
answer = ~sum; // truncate to 16 bits
return (answer);
}
//---------------------------------------------------------------------------
#pragma package(smart_init)
//调用
// TPing myping(Handle,ListBox1);
// myping.Init();
// myping.UserPing(EdtsrcIP->Text.c_str());
// myping.UnLoad();

skimwater 2001-07-09
  • 打赏
  • 举报
回复
inet_addr()这是API函数啊!
我等着你给分啦。
airhorse 2001-07-09
  • 打赏
  • 举报
回复

inet_addr:win api
softer 2001-07-09
  • 打赏
  • 举报
回复
to 掠水惊鸿
还少函数inet_addr(),这函数是如何编
cobi 2001-07-09
  • 打赏
  • 举报
回复
gz
skimwater 2001-07-09
  • 打赏
  • 举报
回复
把好东西给你了,记得给分哦!
function PingHost(HostIP: String): Boolean;
type
PIPOptionInformation = ^TIPOptionInformation;
TIPOptionInformation = packed record
TTL: Byte;
TOS: Byte;
Flags: Byte;
OptionsSize: Byte;
OptionsData: PChar;
end;

PIcmpEchoReply = ^TIcmpEchoReply;
TIcmpEchoReply = packed record
Address: DWORD;
Status: DWORD;
RTT: DWORD;
DataSize: Word;
Reserved: Word;
Data: Pointer;
Options: TIPOptionInformation;
end;
TIcmpCreateFile = function: THandle; stdcall;
TIcmpCloseHandle = function(IcmpHandle: THandle): Boolean; stdcall;
TIcmpSendEcho = function(IcmpHandle:THandle;
DestinationAddress: DWORD;
RequestData: Pointer;
RequestSize: Word;
RequestOptions: PIPOptionInformation;
ReplyBuffer: Pointer;
ReplySize: DWord;
Timeout: DWord
): DWord; stdcall;
var
hICMP : THandle;
hICMPdll : THandle;
IcmpCreateFile : TIcmpCreateFile;
IcmpCloseHandle : TIcmpCloseHandle;
IcmpSendEcho : TIcmpSendEcho;
pIPE : PIcmpEchoReply;// ICMP Echo reply buffer
FIPAddress : DWORD;
FSize : DWORD;
FTimeOut : DWORD;
BufferSize : DWORD;
pReqData,pRevData:PChar;
MyString:string;
begin
Result := False;
hICMPdll := LoadLibrary('icmp.dll');
if hICMPdll = 0 then exit;

@ICMPCreateFile := GetProcAddress(hICMPdll, 'IcmpCreateFile');
@IcmpCloseHandle := GetProcAddress(hICMPdll,'IcmpCloseHandle');
@IcmpSendEcho := GetProcAddress(hICMPdll, 'IcmpSendEcho');

hICMP := IcmpCreateFile;

if (hICMP = INVALID_HANDLE_VALUE) then exit;

FIPAddress := inet_addr(PChar(HostIP));
MyString := 'Hello,World'; //send data buffer
pReqData := PChar(MyString);

FSize := 40; //receive data buffer
BufferSize := SizeOf(TICMPEchoReply) + FSize;
GetMem(pIPE,BufferSize);
FillChar(pIPE^, SizeOf(pIPE^), 0);
GetMem(pRevData,FSize);
pIPE^.Data := pRevData;

FTimeOut := 4000;
try
Result := IcmpSendEcho(hICMP, FIPAddress, pReqData,
Length(MyString),nil,pIPE,BufferSize,FTimeOut)>0;
finally
IcmpCloseHandle(hICMP);
FreeLibrary(hICMPdll);
FreeMem(pRevData);
FreeMem(pIPE);
end;
end;
shuyi 2001-07-09
  • 打赏
  • 举报
回复
调用icmp.dll中的函数,好象定义方法为TIcmpSendEcho=function(IcmpHandle:THandle;
DestinaionAddress:DORD;RequestDate:Pointer;RequestSize:Word;
我不懂电脑 2001-07-09
  • 打赏
  • 举报
回复
心情极坏
Michaelyfj 2001-07-09
  • 打赏
  • 举报
回复
to all:
我试一试!

5,392

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧