MFC 实现ping功能。整理来的
[cpp]<pre name="code" class="cpp">
// 参数:
// szTarget目标地址(可以是域名、IP地址)
// dwTime返回时间;如果是超时,等于INFINITE
BOOL Ping(LPCTSTR szTarget, DWORD &dwTime)
{
BOOL bSuccess = FALSE;
dwTime = INFINITE;
if(szTarget == NULL)
{
TRACE0("Target Is NULL\n");
return FALSE;
}
TCHAR szCmdLine[80];
if(_sntprintf(szCmdLine, sizeof(szCmdLine) / sizeof(TCHAR),
_T("ping.exe -n 1 %s"), szTarget) == sizeof(szCmdLine) / sizeof(TCHAR))
{
TRACE0("Target Is Too Long\n");
return FALSE;
}
HANDLE hWritePipe = NULL;
HANDLE hReadPipe = NULL;
HANDLE hWriteShell = NULL;
HANDLE hReadShell = NULL;
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(sa));
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if(CreatePipe(&hReadPipe, &hReadShell, &sa, 0)
&& CreatePipe(&hWriteShell, &hWritePipe, &sa, 0))
{
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdInput = hWriteShell;
si.hStdOutput = hReadShell;
si.hStdError = hReadShell;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
int nMin = -1, nMax = -1, nAvg = -1;
if(CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
if(WaitForSingleObject(pi.hProcess, 10000) == WAIT_OBJECT_0)
{
TCHAR szBuffer[1024];
DWORD dwBytes;
if(ReadFile(hReadPipe, szBuffer, sizeof(szBuffer), &dwBytes, NULL))
{
szBuffer[dwBytes] = '\0';
LPTSTR lpszTime = NULL;
lpszTime = _tcsstr(szBuffer, _T("Request timed out"));
if(lpszTime == NULL)
{
lpszTime = _tcsstr(szBuffer, _T("Minimum"));
if(lpszTime != NULL)
{
if(_stscanf(lpszTime, _T("Minimum = %dms, Maximum = %dms, Average = %dms"),
&nMin, &nMax, &nAvg) == 3)
{
TRACE3("%d, %d, %d\n", nMin, nMax, nAvg);
dwTime = nAvg;
bSuccess = TRUE;
}
}
else
{
TRACE0("PING FORMAT is Error\n");
}
补充:软件开发 , Vc ,