极其常用的Ping命令通过向计算机发送ICMP Echo请求报文并且监听回应报文的返回,以校验与远程计算机或本地计算机的连接。
使用ICMP.DLL实现Ping
在Windows平台编程中实现Ping的一个最简单方法是调用ICMP.DLL这个动态链接库,引用ICMP.DLL中的三个函数即可:
HANDLE IcmpCreateFile(void);
这个函数打开个ICMP Echo请求能使用的句柄;
BOOL IcmpCloseHandle(HANDLE IcmpHandle);
这个函数关闭由IcmpCreateFile打开的句柄;
DWORD IcmpSendEcho( HANDLE IcmpHandle, // IcmpCreateFile打开的句柄 IPAddr DestinationAddress, //Echo请求的目的地址 LPVOID RequestData, //发送数据buffer WORD RequestSize, //发送数据长度 PIP_OPTION_INFORMATION RequestOptions, // IP_OPTION_INFORMATION指针 LPVOID ReplyBuffer, //接收回复buffer DWORD ReplySize, //接收回复buffer大小 DWORD Timeout //等待超时 );
这个函数发送Echo请求并等待回复或超时。
把这个函数和相关数据封装成一个类CPing,CPing类的头文件如下:
class CPing { public: CPing(); ~CPing(); BOOL Ping(char* strHost); private: // ICMP.DLL 导出函数指针 HANDLE (WINAPI *pIcmpCreateFile)(VOID); BOOL (WINAPI *pIcmpCloseHandle)(HANDLE); DWORD (WINAPI *pIcmpSendEcho)(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD); HANDLE hndlIcmp; // 加载ICMP.DLL库句柄 BOOL bValid; //是否构造(获得ICMP.DLL导出函数指针和初始化WinSock)成功 };
CPing类的构造函数获得ICMP.DLL中导出函数的指针并初始化WinSock:
CPing::CPing() { bValid = FALSE; WSADATA wsaData; int nRet; // 动态加载ICMP.DLL hndlIcmp = LoadLibrary("ICMP.DLL"); if (hndlIcmp == NULL) { ::MessageBox(NULL, "Could not load ICMP.DLL", "Error:", MB_OK); return; }
// 获得ICMP.DLL中导出函数指针 pIcmpCreateFile = (HANDLE (WINAPI *)(void))GetProcAddress((HMODULE)hndlIcmp,"IcmpCreateFile"); pIcmpCloseHandle = (BOOL (WINAPI *)(HANDLE))GetProcAddress((HMODULE)hndlIcmp,"IcmpCloseHandle"); pIcmpSendEcho = (DWORD (WINAPI *)(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD)) GetProcAddress((HMODULE)hndlIcmp,"IcmpSendEcho");
// 检查所有的指针 if (pIcmpCreateFile == NULL || pIcmpCloseHandle == NULL ||pIcmpSendEcho == NULL) { ::MessageBox(NULL, "Error loading ICMP.DLL", "Error:", MB_OK); FreeLibrary((HMODULE)hndlIcmp); return; }
共9页: 上一页 1 [2] [3] [4] [5] [6] [7] [8] [9] 下一页
|