#include <winsock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
#include <icmpapi.h>
void Ctest111Dlg::CEPing(CString cIPAddr,CListBox * pListBox,UINT uiTimes)//CWnd * pWnd ,
{
WSAData wsaData;
//初始化Socket动态链接库
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
{
return ;
}
// 最少 ping 的次数
if (uiTimes == 0)
uiTimes = 4;
//将IP地址转换成单字节
char szDestIPAddr[255];
ZeroMemory(szDestIPAddr,255);
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK
,cIPAddr.GetBuffer(cIPAddr.GetLength()),cIPAddr.GetLength()
,szDestIPAddr,cIPAddr.GetLength(),NULL,NULL);
IPAddr ipAddr;
//将目标字符串IP地址转换成IPAddr结构
ipAddr = inet_addr(szDestIPAddr);
if (ipAddr == INADDR_NONE)
{
AfxMessageBox(_T("地址无效"));
return ;
}
// 打开ping服务
HANDLE hIP = IcmpCreateFile();
if (hIP == INVALID_HANDLE_VALUE) {
AfxMessageBox(_T("不能打开Ping服务"));
return ;
}
// 构造ping数据包
char acPingBuffer[64];
memset(acPingBuffer, '*', sizeof(acPingBuffer));
PICMP_ECHO_REPLY pIpe = (PICMP_ECHO_REPLY)GlobalAlloc( GMEM_FIXED | GMEM_ZEROINIT,
sizeof(ICMP_ECHO_REPLY) + sizeof(acPingBuffer));
if (pIpe == 0) {
AfxMessageBox(_T("分配ping包缓冲区失败"));
return ;
}
CString m_recv;
// 发送ping数据包
m_recv = _T("ping ")+cIPAddr+_T(" with 64 Bytes");
pListBox->AddString(m_recv);
for (UINT i=0; i<uiTimes; i++)
{
//发送ping服务包,等待接收时间为1秒
DWORD dwStatus = IcmpSendEcho(hIP,ipAddr,
acPingBuffer, sizeof(acPingBuffer), NULL, pIpe,
sizeof(ICMP_ECHO_REPLY) + sizeof(acPingBuffer), 4000);
//当dwStatus不等于0,代表接收到回应
if (dwStatus != 0)
{
m_recv.Format(_T("Reply From %d.%d.%d.%d :bytes=%d time=%dMS TTL")
,int(LOBYTE(LOWORD(pIpe->Address)))
,int(HIBYTE(LOWORD(pIpe->Address)))
,int(LOBYTE(HIWORD(pIpe->Address)))
,int(HIBYTE(HIWORD(pIpe->Address)))
,int(pIpe->DataSize)
,int(pIpe->RoundTripTime)
,int(pIpe->Options.Ttl));
//pListBox->InsertString(0,m_recv);
pListBox->AddString(m_recv);
Sleep(500);
// 显示最后一行
// pListBox->SetLocale(i);
// pListBox->SetSel(i,TRUE);
// pListBox->SetTopIndex(i);
}
else
{
pListBox->AddString(_T("Error obtaining info from ping packet."));
}
//pWnd->UpdateWindow();
}
//释放已分配的内存
GlobalFree(pIpe);
//关闭Ping服务
IcmpCloseHandle(hIP);
//释放Socket资源
WSACleanup();
}