C/C++ 通过管道的方式调用Windows ping命令 且 不显示黑窗口(cmd 窗口)

C/C++ 通过管道的方式调用Windows ping命令 且 不显示黑窗口(cmd 窗口)

目录

简介

通常我们使用Windows的Ping命令,会把Ping的详细结果显示到cmd窗中,所以不能直接隐藏cmd窗口。解决思路:我们可以把ping的结果直接写到管道中,然后直接拷贝到定义的char数组中。通过解析收到的数据,就可以知道是否Ping成功了。这样的方式可以屏蔽cmd窗口。

代码详解

#include 
#include 
#include 
#include 

using namespace std;

bool pingOnlyOnce(const string IP)
{
    bool bRet = false;

    // chcp 437 这个命令把操作系统默认语言强制转换成英文显示,便于解析。
    const string PING_CMD = "chcp 437 && ping -n 1 ";
    string PING_CMD_IP(PING_CMD);
    PING_CMD_IP.append(IP);

    char pingResult[512] = { 0 };

    // 通过管道调用Ping命令
    FILE *pPipe;
    if ( NULL == (pPipe = _popen(PING_CMD_IP.c_str(), "rt")) )
    {
        exit(1);
    } 

    bRet = false;

    // 解析ping结果
    while(fgets(pingResult, 512, pPipe))
    {
        // Ping 失败通常有两种情况:一种是timeout;
        //一种是,路由器返回"Destination host unreachable",此时ping命令还没有timeout。所以在ping结果中,两种情况存在任意一种,都是ping失败了。
        if ( strstr(pingResult, "Request timed out") != NULL 
        || strstr(pingResult, "Destination host unreachable") != NULL)
        {
            bRet = false;
            break;
        }
        // 在Ping一次的情况下,Ping成功一定会有"Lost =0"字符串出现。
        else if ( strstr(pingResult, "Lost =0") != NULL )
        {
            bRet = true;
            break;
        }
        // 打印 行 ping结果
        printf("%s", pingResult);
    }

    _pclose(pPipe);
    return bRet;
}

int main()
{
    bool bPingSuccess = false;

    bPingSuccess = pingOnlyOnce("127.0.0.1");
    if ( bPingSuccess )
    {
        cout << "PING SUCCESS !" << endl;
    }
    else
    {
        cout << "PING FAILED !" << endl;
    }

    system("pause");
    return 0;
}

后记

运行上述代码,也会显示黑窗口,但是这个黑窗口是Application本身的黑窗口,不是cmd的窗口,把上述函数集成到你的代码中就不会有黑窗口了。




PS:亲,如果对你有帮助,就送个赞吧,满足一下LZ的虚荣心 ^ - ^

你可能感兴趣的:(Demo集,windows,cmd,c-c++,ping)