码迷,mamicode.com
首页 > 其他好文 > 详细

寻找正在连接中的网络连接

时间:2015-07-26 19:14:30      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:



寻找正在连接中的网络连接,并开启网络连接的网络连接共享功能。

注意:要设置为管理员权限启动工程。否则EnableSharing会失败。

#include <Windows.h>
#include <NetCon.h>
#include <locale>
#include <stdio.h>
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"Rpcrt4.lib")//GUID
//启用、禁用网卡
#pragma comment(lib,"ole32.lib")

int main(int argc, char* argv[])
{
    INetConnectionManager *pManager=NULL;
    INetConnection *pConnection=NULL;
    IEnumNetConnection *pEnum=NULL;
    ULONG           celtFetched;
    INetSharingManager *pNetSharingManager=NULL;
    INetConnectionProps *pProps=NULL;
    INetSharingConfiguration *pConfiguration=NULL;
    NETCON_PROPERTIES*   properties=NULL;
    NETCON_MEDIATYPE   mediatype;

    setlocale(LC_CTYPE, "");
    CoInitialize(NULL);
    CoCreateInstance(CLSID_ConnectionManager, NULL, CLSCTX_SERVER, IID_INetConnectionManager, (void**)&pManager);
    if(pManager == NULL)
    {
        printf("获取接受失败,Error:%d\n",GetLastError());
        return 0;
    }
    pManager->EnumConnections(NCME_DEFAULT, &pEnum);

    while(  pEnum->Next(1, &pConnection, &celtFetched) == S_OK   )
    {
        pConnection->GetProperties(&properties);

        if(properties->Status == NCS_CONNECTED)
        {
            if(properties->dwCharacter & NCCF_INCOMING_ONLY == 1)
            {
                wprintf(L"\"%S\"正处于连接状态,但是此连接无法共享!确保至少有2个网络连接!\n",properties->pszwName);
                break;
            }
            CoCreateInstance(CLSID_NetSharingManager, NULL, CLSCTX_SERVER, IID_INetSharingManager, (void**)&pNetSharingManager);
            if(pNetSharingManager == NULL)
            {
                printf("获取接受失败,Error:%d\n",GetLastError());
                break;
            }
            wprintf(L"发现\"%s\"正处于连接状态。尝试开启共享...\n",properties->pszwName);

            if(properties->MediaType >= NCM_DIRECT && properties->MediaType <=NCM_PPPOE)
            {
                pNetSharingManager->get_INetSharingConfigurationForINetConnection(pConnection,
                    &pConfiguration);
                if(pConfiguration && SUCCEEDED(pConfiguration->EnableSharing(ICSSHARINGTYPE_PUBLIC)))
                {
                    wprintf(L"成功设置\"%s\"为共享状态!\n",properties->pszwName);
                    break;
                }
            }
            wprintf(L"设置\"%s\"共享状态失败!Error:%d\n",properties->pszwName,GetLastError());
        }
    }


    if(pManager) pManager->Release();
    if(pConnection) pConnection->Release();
    if(pEnum) pEnum->Release();
    if(pNetSharingManager) pNetSharingManager->Release();
    if(pConfiguration) pConfiguration->Release();
    CoUninitialize();
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

寻找正在连接中的网络连接

标签:

原文地址:http://blog.csdn.net/jiangqin115/article/details/47070325

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!