我如何用c++在我的Windows计算机上ping远程计算机

How can i ping remote computer on my Windows computer with c++?

本文关键字:计算机 ping Windows 我的 何用 c++      更新时间:2023-10-16

我使用了下面的代码。它可以工作,但是在Visual Studio调试模式下,如果你停止调试,计算机会给出蓝屏,所以它是没有用的。我做了一些研究,发现这是icmpapi的一个常见错误。有什么办法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);
        }

小心。:

//https://msdn.microsoft.com/en-us/library/windows/desktop/aa366050 (v = vs.85) . aspx

代码可以工作,但是如果你粘贴/复制这段代码,就会错过重要的一点:失踪的自由(ReplyBuffer)

相关文章: