如何使用 C++ ping 我的 Windows 计算机上的远程计算机? [英] How can i ping remote computer on my Windows computer with c++?
本文介绍了如何使用 C++ ping 我的 Windows 计算机上的远程计算机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了以下代码.它可以工作,但是在 Visual Studio 中的调试模式下,如果您停止调试,计算机会出现蓝屏,因此它没有用.我做了一些研究,发现这是 icmpapi 的一个常见错误.有没有办法ping计算机C++?
I used below code. It works, but in debug mode in Visual Studio if you stop the debug the computer gave blue screen so it is not useful. I did some research and i found this is a common bug for icmpapi. Is there a any way to ping computer c++?
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
//Declare and initialize variables
HANDLE hIcmpFile;
unsigned long ipaddr = INADDR_NONE;
DWORD dwRetVal = 0;
DWORD dwError = 0;
char SendData[] = "Data Buffer";
LPVOID ReplyBuffer = NULL;
DWORD ReplySize = 0;
QByteArray ipArray = computerIt->GetIP().toLocal8Bit();
const char *hostIP = ipArray.data();
ipaddr = inet_addr(hostIP);
if ( ipaddr == INADDR_NONE )
{
EventLogger::LogMessage(true, "<%s> Computer in <%s> Computer Group, IP initialization failed. (inet_addr(hostIP))", computerIt->GetName().toUtf8().constData(), computerGroupIt->GetName().toUtf8().constData());
break;
}
hIcmpFile = IcmpCreateFile();
if ( hIcmpFile == INVALID_HANDLE_VALUE )
{
EventLogger::LogMessage(true, "<%s> Computer in <%s> Computer Group, IcmpCreatefile returned error", computerIt->GetName().toUtf8().constData(), computerGroupIt->GetName().toUtf8().constData());
break;
}
// Allocate space for at a single reply
ReplySize = sizeof (ICMP_ECHO_REPLY) + sizeof (SendData) + 8;
ReplyBuffer = (VOID *) malloc(ReplySize);
if ( ReplyBuffer == NULL )
{
EventLogger::LogMessage(true, "<%s> Computer in <%s> Computer Group, unable to allocate memory for reply buffer", computerIt->GetName().toUtf8().constData(), computerGroupIt->GetName().toUtf8().constData());
break;
}
// Starting pinging
dwRetVal = IcmpSendEcho2(hIcmpFile, NULL, NULL, NULL,
ipaddr, SendData, sizeof (SendData), NULL,
ReplyBuffer, ReplySize, 1000);
if ( dwRetVal == 0 )
{
computerIt->SetAliveStatus(false);
}
else
{
computerIt->SetAliveStatus(true);
}
推荐答案
小心.在:
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa366050(v=vs.85).aspx
代码有效,但如果您粘贴/复制此代码,则缺少重要的一点:MISSING free(ReplyBuffer)
the code works , BUT is missing an IMPORTANT POINT if you paste/copy this code: MISSING free(ReplyBuffer)
这篇关于如何使用 C++ ping 我的 Windows 计算机上的远程计算机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文