[英]How can i ping remote computer on my Windows computer with 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. 它可以工作,但是在Visual Studio的调试模式下,如果停止调试,则计算机会显示蓝屏,因此它没有用。 I did some research and i found this is a common bug for icmpapi. 我做了一些研究,发现这是icmpapi的常见错误。 Is there a any way to ping computer c++? 有没有办法ping计算机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);
}
In the above code there is bug in IcmpSendEcho2 method! 在上面的代码中,IcmpSendEcho2方法中有错误! It is only seen in debug mode! 仅在调试模式下可见! (See the link) https://msdn.microsoft.com/en-us/library/windows/desktop/aa366050(v=vs.85).aspx (请参阅链接) https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa366050 ( v= vs.85) .aspx
I used raw ping methods for the ping operation. 我对ping操作使用了原始ping方法。 It is much slower but it is safety! 它慢得多,但是很安全!
You can check raw ping method: http://tangentsoft.net/wskfaq/examples/rawping.html 您可以检查原始ping方法: http : //tangentsoft.net/wskfaq/examples/rawping.html
be careful. 小心。 at: 在:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366050(v=vs.85).aspx // https://msdn.microsoft.com/zh-CN/library/windows/desktop/aa366050(v=vs.85).aspx
the code works , BUT is missing an IMPORTANT POINT if you paste/copy this code: MISSING free(ReplyBuffer) 该代码有效,但是如果粘贴/复制此代码,则缺少重要点:MISSING free(ReplyBuffer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.