用VC调用DOS命令来实现PING功能

BOOL PingNetIP(CString szIp)
{ 
	SECURITY_ATTRIBUTES   sa;  
	HANDLE   hRead,hWrite;  

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);  
	sa.lpSecurityDescriptor   =   NULL;  
	sa.bInheritHandle   =   TRUE;  
	if (!CreatePipe(&hRead,&hWrite,&sa,0)) 
	{  
		return FALSE;  
	}    
	STARTUPINFO si;  
	PROCESS_INFORMATION pi;    
	si.cb = sizeof(STARTUPINFO);  
	GetStartupInfo(&si);    
	si.hStdError = hWrite;  
	si.hStdOutput = hWrite;  
	si.wShowWindow = SW_HIDE;  
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;  
	CString pIP;
	pIP.Format("ping -n 1 %s", szIp);
	if (!CreateProcess(NULL, pIP.GetBuffer(0), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))  
	{
		return FALSE;  
	}  
	CloseHandle(hWrite);  
	char buffer[4096] = "";
	char *pBuffer = buffer;
	DWORD bytesRead;    
	while(1)   
	{  
		if (ReadFile(hRead, pBuffer, 4095, &bytesRead,NULL)   ==   NULL)  
			break;  
		pBuffer += bytesRead;
		Sleep(200);    
	}    

	CString cResult(buffer);
	if (cResult.Find("请求超时") != -1 || cResult.Find("无法访问目标主机") != -1)
	{
		return FALSE;
	}

	return TRUE;

猜你喜欢

转载自blog.csdn.net/fcxzqz/article/details/44219537