C++ 判断当前网络是否正常,

#include<iostream>

#include <Netlistmgr.h>
static bool checkIsNetwork()
{
    Sleep(1000);
    CoInitialize(NULL);
    //  通过NLA接口获取网络状态    
    IUnknown *pUnknown = NULL;  
    BOOL   bOnline = false;  
    //是否在线      
    HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL, IID_IUnknown, (void **)&pUnknown);  //创建一个com对象
    if (SUCCEEDED(Result))   
    {
        INetworkListManager *pNetworkListManager = NULL; 
        if (pUnknown)           
            Result = pUnknown->QueryInterface(IID_INetworkListManager, (void **)&pNetworkListManager);
        if (SUCCEEDED(Result))      
        {
            VARIANT_BOOL IsConnect = VARIANT_FALSE;
            if (pNetworkListManager)           
                Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect);
            if (SUCCEEDED(Result))          
            {
                bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
            }
        }        
        if (pNetworkListManager)           
            pNetworkListManager->Release();
    }   
    if (pUnknown)        
        pUnknown->Release();
    CoUninitialize();
    return bOnline;
}

HANDLE g_hMutex = NULL;
//线程函数
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
    Sleep(1000);
    if (!checkIsNetwork())
    {
        WaitForSingleObject(g_hMutex, INFINITE);  //等待线程同步
        std::cout << "网络已断开" << std::endl;        
        ReleaseMutex(g_hMutex);   //释放互斥量
    }
    else
    {
        WaitForSingleObject(g_hMutex, INFINITE);
        std::cout << "网络正常" << std::endl;
        ReleaseMutex(g_hMutex);

    }
    return 0L;
}

int main()
{
    g_hMutex = CreateMutex(NULL, FALSE, NULL);//创建互斥量
    while (1)
    {
        Sleep(1000);
        //创建一个线程
        HANDLE thread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);

        //关闭线程
        CloseHandle(thread);
    }

    return 0;
}

原文地址:https://blog.csdn.net/qq_31815979/article/details/105112948

posted @ 2020-05-22 06:53  神迹丶  阅读(2074)  评论(0编辑  收藏  举报
网站已运行: