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

我怕爱的太早我们不能终老 提交于 2021-02-20 03:55:11

问题


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);
        }

回答1:


be careful. at:

// https://msdn.microsoft.com/en-us/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)



来源:https://stackoverflow.com/questions/32179834/how-can-i-ping-remote-computer-on-my-windows-computer-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!