WINCE 实现WIFI连接功能(WZC)

    利用微软自带的WZC函数来重新编写一个独立于系统的WIFI连接程序。 本人实际操作后,实现扫描,连接等等功能。但是WINCE系统确实是太久远的系统了,此篇文章也是供大家了解一下,WINCE下自带的WIFI功能。

以下是关键节点,大家可以参考一下。

//WCZ库文件

#include <Windows.h>    
#include "wzcsapi.h"
#include <vector>
#include "iphlpapi.h"
#include <afxmt.h>

#pragma comment(lib,"iphlpapi.lib")
#pragma comment(lib,"wzcsapi.lib") 
#pragma comment(lib,"cclib.lib")

//SSID基本信息
typedef struct tag_SsidInfo    
{    
	TCHAR sSsid[MAX_PATH];                                         // 无线AP SSID
	int nRssi;                                                     // 信号强度
	NDIS_802_11_NETWORK_INFRASTRUCTURE InfrastructureMode;         // bAdhoc: 是否点对点的 WIFI 连接
	ULONG ulPrivacy;                                               // 加密模式(WEP/WPA....)
	NDIS_802_11_AUTHENTICATION_MODE AuthenticationMode;            // ndisMode 认证模式(Open/Share)
	int iKeyIndex;                                                 // 密匙索引
	TCHAR pKey[60];                                                // 密码
	int iEapType;                                                  // 802.11 认证模式
	int ID;                                                        // ID标识符
}SsidInfo;

//CWLanConfig   WLAN配置类信息                                      
                                                                   
class CWLanConfig                        
{
public:
	CWLanConfig()
	{
		m_fWZCInit = FALSE;
		m_CardIndex = -1;			
	}

	BOOL InitZeroConfig(void);                                                                    //初始化配置
	void PrintfMacAddress(IN PRAW_DATA prdMAC);                                                   //显示MAC地址
	void PrintSSID(PRAW_DATA prdSSID, WCHAR* tSsid );                                             //显示SSID
	PTCHAR SupportedRate(IN BYTE ucbRawValue);                                                    //支持速率
	UINT ChannelNumber(IN ULONG ulFrequency_kHZ);                                                 //频率数
	void EnumWirelessNetwordCard(void);                                                           //权举无线网卡列表
	void WirelessQuery(void);                                                                     //无线询问,获取WLAN网卡基本信息
	void GetWirelseeListSSID(const PRAW_DATA prdBSSIDList,PRAW_DATA prdSSID,vector<SsidInfo> &SsidList);                    //获取SSID基本信息

	BOOL WirelessConnect(PTCHAR pCard, PTCHAR pSSID,NDIS_802_11_NETWORK_INFRASTRUCTURE infr, ULONG ulPrivacy,   NDIS_802_11_AUTHENTICATION_MODE ndisMode, PTCHAR pKey,int iKeyIndex, int iEapType ,int isconnectid);         //连接网络函数
	void AddToPreferredNetworkList( IN WCHAR *szWiFiCard, IN WZC_WLAN_CONFIG& wzcConfig1, IN WCHAR *szSsidToConnect);                             //加入到WINDOUS的首选WIFI网络
	void ResetPreferredList(PTCHAR pCard);                                                                                                        //断开连接函数
	BOOL InterpretEncryptionKeyValue(IN OUT WZC_WLAN_CONFIG& wzcConfig, IN int iKeyIndex, IN PTCHAR pKey, IN BOOL bNeed8021X);                    //说明加密键值 

private:
	typedef DWORD (*PFN_WZCQueryInterfaceEx)(LPWSTR pSrvAddr,DWORD dwInFlags,PINTF_ENTRY_EX pIntf,LPDWORD pdwOutFlags);
	typedef DWORD (*PFN_WZCSetInterfaceEx)(LPWSTR pSrvAddr,DWORD dwInFlags,PINTF_ENTRY_EX pIntf,LPDWORD pdwOutFlags);
	typedef DWORD (*PFN_WZCRefreshInterfaceEx)(LPWSTR pSrvAddr,DWORD dwInFlags,PINTF_ENTRY_EX pIntf,LPDWORD pdwOutFlags);
	typedef DWORD (*PFN_WZCEnumEapExtensions)(DWORD *pdwNumOfExtensions,PEAP_EXTENSION_INFO *ppEapExtensions);
	typedef DWORD (*PFN_WZCDeleteIntfObjEx)(PINTF_ENTRY_EX pIntf);
	typedef DWORD (*PFN_WZCQueryContext)(LPWSTR pSrvAddr,DWORD dwInFlags,PWZC_CONTEXT pContext,LPDWORD pdwOutFlags);
	typedef DWORD (*PFN_WZCSetContext)(LPWSTR pSrvAddr,DWORD dwInFlags,PWZC_CONTEXT pContext,LPDWORD pdwOutFlags);
	typedef VOID  (*PFN_WZCPassword2Key)(PWZC_WLAN_CONFIG pwzcConfig, LPCSTR cszPassword);

	PFN_WZCQueryInterfaceEx    pfnWZCQueryInterfaceEx;
	PFN_WZCSetInterfaceEx      pfnWZCSetInterfaceEx;
	PFN_WZCRefreshInterfaceEx  pfnWZCRefreshInterfaceEx;
	PFN_WZCEnumEapExtensions   pfnWZCEnumEapExtensions;
	PFN_WZCDeleteIntfObjEx     pfnWZCDeleteIntfObjEx;
	PFN_WZCQueryContext        pfnWZCQueryContext;
	PFN_WZCSetContext          pfnWZCSetContext;
	PFN_WZCPassword2Key        pfnWZCPassword2Key;

	BOOL			m_fWZCInit;
	int				m_CardIndex;
	TCHAR			m_WirelessCard[MAX_PATH];	
};

/************************************************************************/
/*   函数名称:  InitZeroConfig()                                        */
/*   函数作用:  进行初始化配置                                          */
/*              检查WZCAPI.dll文件是否在WINCE系统中                     */
/************************************************************************/

BOOL CWLanConfig::InitZeroConfig()
{
	HINSTANCE hWZCLib = NULL;
	
	if (m_fWZCInit) 
	{
		return TRUE; // Already initialized
	}

	// See if zero config API present in system
	if ((hWZCLib = LoadLibrary(L"wzcsapi.dll")) == NULL)
	{
	    //RETAILMSG(1,(TEXT("!WZCUI: WZCAPI.DLL not present in system\r\n")));
		return FALSE;
	}

	pfnWZCQueryInterfaceEx    = (PFN_WZCQueryInterfaceEx)GetProcAddress(hWZCLib,L"WZCQueryInterfaceEx");
	pfnWZCSetInterfaceEx      = (PFN_WZCSetInterfaceEx)GetProcAddress(hWZCLib,L"WZCSetInterfaceEx");
	pfnWZCRefreshInterfaceEx  = (PFN_WZCRefreshInterfaceEx)GetProcAddress(hWZCLib,L"WZCRefreshInterfaceEx");
	pfnWZCEnumEapExtensions   = (PFN_WZCEnumEapExtensions)GetProcAddress(hWZCLib,L"WZCEnumEapExtensions");
	pfnWZCDeleteIntfObjEx     = (PFN_WZCDeleteIntfObjEx)GetProcAddress(hWZCLib,L"WZCDeleteIntfObjEx");
	pfnWZCQueryContext		  = (PFN_WZCQueryContext)GetProcAddress(hWZCLib,L"WZCQueryContext");
	pfnWZCSetContext		  = (PFN_WZCSetContext)GetProcAddress(hWZCLib,L"WZCSetContext");
	pfnWZCPassword2Key        = (PFN_WZCPassword2Key)GetProcAddress(hWZCLib,L"WZCPassword2Key");

	if (
		(pfnWZCQueryInterfaceEx == NULL)   ||
		(pfnWZCSetInterfaceEx == NULL)     ||
		(pfnWZCRefreshInterfaceEx == NULL) ||
		(pfnWZCEnumEapExtensions == NULL)  ||
		(pfnWZCDeleteIntfObjEx == NULL)    ||
		(pfnWZCSetContext == NULL)         ||
		(pfnWZCQueryContext == NULL)
		) 
	{
        //RETAILMSG(1,(TEXT("!WZCUI: WZCAPI.DLL not present in system\r\n")));
		return FALSE;
	}

	m_fWZCInit = TRUE;
	return TRUE; 

}

/************************************************************************/
/*  函数名称: EnumWirelessNetwordCard()                                 */
/*  函数作用: enumerate wireless network cards detected by WLan         */
/*            用WLAN侦查无线网卡                                        */
/************************************************************************/

void CWLanConfig::EnumWirelessNetwordCard()                             // arg none
{
	INTFS_KEY_TABLE IntfsTable;
	IntfsTable.dwNumIntfs = 0;
	IntfsTable.pIntfs = NULL;
	
	_tcscpy(m_WirelessCard, TEXT(""));

	DWORD dwStatus = WZCEnumInterfaces(NULL, &IntfsTable);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WZCEnumInterfaces() error 0x%08X\n"),dwStatus));
		return;
	}

	// print the GUIDs
	// note that in CE the GUIDs are simply the device instance name
	// i.e XWIFI11B1, CISCO1, ISLP2, ...
    //

	if (!IntfsTable.dwNumIntfs)
	{
	    //RETAILMSG(DBG_MSG, (TEXT("System has no wireless card.\n")));
		return;
	}
	
	m_CardIndex = IntfsTable.dwNumIntfs;

	//RETAILMSG(DBG_MSG, (TEXT("Enum %d Wiless Net Card:"),m_CardIndex));

	for (uint i = 0; i < IntfsTable.dwNumIntfs; i++)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WIFI Card [%d] = %s\n"), i, IntfsTable.pIntfs[i].wszGuid));
		//nStr.Format(_T("WIFI Card [%d] = %s"), i, IntfsTable.pIntfs[i].wszGuid);
		//g_MainDlg->m_listbox.AddString(nStr);
	}

	_tcscpy(m_WirelessCard, IntfsTable.pIntfs[0].wszGuid);
    
	// need to free memory allocated by WLan for us.
	LocalFree(IntfsTable.pIntfs);
}

/********************************************************************************/
/*  PrintfMacAddress()   显示网址地址                                           */
/*  some RAW_DATA is a MAC ADDRESS,this function is for printing MAC ADDRESS    */                                                                
/********************************************************************************/

void CWLanConfig::PrintfMacAddress(IN PRAW_DATA prdMAC)
{
	if (prdMAC == NULL || prdMAC->dwDataLen == 0)
	{
		//RETAILMSG(DBG_MSG, (TEXT("<NULL>")));
	}
	else if (prdMAC->dwDataLen != 6)
	{
		//RETAILMSG(DBG_MSG, (TEXT("<INVLID MAC>")));
	}
	else
	{
		/*RETAILMSG(DBG_MSG, (TEXT("%02X:%02X:%02X:%02X:%02X:%02X"),
			prdMAC->pData[0],
			prdMAC->pData[1],
			prdMAC->pData[2],
			prdMAC->pData[3],
			prdMAC->pData[4],
			prdMAC->pData[5]));*/
	}
}

/************************************************************************/
/*   PrintSSID() 显示无线网卡的SSID名称                                 */   
/*   some RAW_DATA is a SSID, this function is for printing SSID        */
/************************************************************************/

void CWLanConfig::PrintSSID(PRAW_DATA prdSSID, WCHAR* tSsid )                       // RAW SSID data
{
	if (prdSSID == NULL || prdSSID->dwDataLen == 0)
	{
		//RETAILMSG(DBG_MSG, (TEXT("<null>")));
	}
	else
	{
		MultiByteToWideChar(CP_ACP,0,(LPCSTR)prdSSID->pData,-1,tSsid,MAX_PATH*2); 		
	}
}

/************************************************************************/
/*  函数名称: SupportedRate()                                           */
/*  函数功能: 支持速率                                                  */
/************************************************************************/

PTCHAR CWLanConfig::SupportedRate(IN BYTE ucbRawValue)
{
	double fRate = ((double)(ucbRawValue & 0x7F)) * 0.5;
	swprintf(g_szSupportedRate, L"%.1f", fRate);
	return g_szSupportedRate;
} 

/************************************************************************/
/*     ChannelNumber()   频率数                                         */
/*     calculate 802.11b channel number for given frequency             */
/*     return 1-14 based on the given ulFrequency_kHz                   */
/*     return 0 for invalid frequency range                             */
/*                                                                      */
/*     2412 MHz = ch-1                                                  */
/*     2417 MHz = ch-2                                                  */
/*     2422 MHz = ch-3                                                  */
/*     2427 MHz = ch-4                                                  */
/*     2432 MHz = ch-5                                                  */
/*     2437 MHz = ch-6                                                  */
/*     2442 MHz = ch-7                                                  */
/*     2447 MHz = ch-8                                                  */
/*     2452 MHz = ch-9                                                  */
/*     2457 MHz = ch-10                                                 */
/*     2462 MHz = ch-11                                                 */
/*     2467 MHz = ch-12                                                 */
/*     2472 MHz = ch-13                                                 */
/*     2484 MHz = ch-14                                                 */
/*                                                                      */
/************************************************************************/

UINT CWLanConfig::ChannelNumber(IN ULONG ulFrequency_kHz)                //  frequency in khz
{
	ULONG ulFrequency_MHz = ulFrequency_kHz / 1000;
	if((2412 <= ulFrequency_MHz) && (ulFrequency_MHz < 2484))
	{
		return ((ulFrequency_MHz - 2412) / 5) + 1;
	}
	else if(ulFrequency_MHz == 2484)
	{
		return 14;
	}
	return 0;   // invalid channel number
}


/********************************************************************************/
/*   函数名称:WirelessQuery()                                                   */
/*   函数作用:Query the WiFi card PMK Cache                                     */
/*   无线询问,获取WLAN网卡基本信息                                              */
/********************************************************************************/

void CWLanConfig::WirelessQuery(void)
{
	TCHAR *szWiFiCard = NULL;

	// wifi card not found
	if (!*m_WirelessCard)
	{
		EnumWirelessNetwordCard();

		if (!*m_WirelessCard)
		{
			//RETAILMSG(DBG_MSG, (TEXT("No Wireless Card.\n")));
			return;
		}		
	}

	szWiFiCard = m_WirelessCard;

	INTF_ENTRY_EX Intf;
	DWORD dwOutFlgs = 0;
	ZeroMemory(&Intf, sizeof(INTF_ENTRY_EX));

	Intf.wszGuid = szWiFiCard;

	DWORD dwStatus = WZCQueryInterfaceEx(NULL, INTF_ALL, &Intf, &dwOutFlgs);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WZCQueryInterfaceEx() error 0x%08X\n"), dwStatus));
		return;
	}

	//RETAILMSG(DBG_MSG, (TEXT("WZCQueryInterfaceEx() for %s\n"),szWiFiCard));
	//RETAILMSG(DBG_MSG, (TEXT("In flags used	=[0x%08X]\n"),INTF_ALL));
	//RETAILMSG(DBG_MSG, (TEXT("Return out flag	=[0x%08X]\n"),dwOutFlgs));

	// GUID (in CE, GUID = instance name)
	//RETAILMSG(DBG_MSG, (TEXT("wzcGuid	=[%s]\n"),Intf.wszGuid));

	// Description 描述
	//RETAILMSG(DBG_MSG, (TEXT("wzcDescr	=[%s]\n"),Intf.wszDescr));

	//  Print BSSID. BSSID is the MAC address of the AP I am connected.
	if (dwOutFlgs & INTF_BSSID)
	{
		//RETAILMSG(DBG_MSG, (TEXT("BSSID=")));
		PrintfMacAddress(&Intf.rdBSSID);

		PRAW_DATA prdMAC = &Intf.rdBSSID;

		if (prdMAC == NULL || prdMAC->dwDataLen == 0 || 
			(!prdMAC->pData[0] && !prdMAC->pData[1] && !prdMAC->pData[2] &&
			!prdMAC->pData[3] && !prdMAC->pData[4] && !prdMAC->pData[5]))
		{
			//RETAILMSG(DBG_MSG, (TEXT("(This wifi card is not associated to any)\n")));
		}
		else
		{
			//RETAILMSG(DBG_MSG, (TEXT("(This wifi card is associated state)\n")));
		}
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("BSSID = <unknown> (not connected)\n")));
	}

	//  Media Type
	if (dwOutFlgs & INTF_NDISMEDIA)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Media Type	=[%d]\n"),Intf.ulMediaType));
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("Media Type	=<unknown>\n")));
	}

	// Configuration Mode
	if (dwOutFlgs & INTF_ALL_FLAGS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Configuration Mode = [0x%08X]\n"), Intf.dwCtlFlags));

		if (Intf.dwCtlFlags & INTFCTL_ENABLED)
		{
			//RETAILMSG(DBG_MSG, (TEXT(" Zero conf enabled for this interface\n")));
		}

		if (Intf.dwCtlFlags & INTFCTL_FALLBACK)
		{
			//RETAILMSG(DBG_MSG, (TEXT(" Attempt to connect to visible non-preferred networks also\n")));
		}

		if (Intf.dwCtlFlags & INTFCTL_OIDSSUPP)
		{
			//RETAILMSG(DBG_MSG, (TEXT(" 802.11 OIDs are supported by the driver/firmware\n")));
		}

		if (Intf.dwCtlFlags & INTFCTL_VOLATILE)
		{
			//RETAILMSG(DBG_MSG, (TEXT(" the service parameters are volatile\n")));
		}

		if (Intf.dwCtlFlags & INTFCTL_POLICY)
		{
			//RETAILMSG(DBG_MSG, (TEXT(" the service parameters policy enforced\n")));
		}
	}

	// Print Infrastructure Mode
	if (dwOutFlgs & INTF_INFRAMODE)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Infrastructure Mode = [%d] "), Intf.nInfraMode));

		if (Intf.nInfraMode == Ndis802_11IBSS)
		{
			//RETAILMSG(DBG_MSG, (TEXT("IBSS net (adhoc net)\n")));
		}
		else if (Intf.nInfraMode == Ndis802_11Infrastructure)
		{
			//RETAILMSG(DBG_MSG, (TEXT("Infrastructure net (connected to an Access Point)\n")));
		}
		else
		{
			//RETAILMSG(DBG_MSG, (TEXT("Ndis802_11AutoUnkonwn\n")));
		}
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("Infrastructure mode = <unknown>\n")));
	}

	// Print Authentication Mode
	if (dwOutFlgs & INTF_AUTHMODE)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Authentication Mode = [%0d] "), Intf.nAuthMode));

		if ((DWORD)Intf.nAuthMode < Ndis802_11AuthModeMax)
		{
			//RETAILMSG(DBG_MSG, (TEXT("%s\n"),g_szAuthenticationMode[Intf.nAuthMode]));
		}
		else
		{
		 	//RETAILMSG(DBG_MSG, (TEXT("<unkonwn>\n")));
		}
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("Authentication Mode = <unkonwn>\n")));
	}

	//RETAILMSG(DBG_MSG, (TEXT("rdNicCapabilities = %d bytes\n"), Intf.rdNicCapabilities.dwDataLen));

	if (Intf.rdNicCapabilities.dwDataLen)
	{
		PINTF_80211_CAPABILITY pCapability = (PINTF_80211_CAPABILITY)Intf.rdNicCapabilities.pData;
		DWORD i;

		//RETAILMSG(DBG_MSG, (TEXT(" dwNumOfPMKIDs	: [%d]\n"), pCapability->dwNumOfPMKIDs));
		//RETAILMSG(DBG_MSG, (TEXT(" dwNumOfAuthEncryptPairs	: [%d]\n"), pCapability->dwNumOfAuthEncryptPairs));

		for (i = 0; i < pCapability->dwNumOfAuthEncryptPairs; i++)
		{
			//RETAILMSG(DBG_MSG, (TEXT("	Pair[%d]\n"), i+1));
			//RETAILMSG(DBG_MSG, (TEXT("	AuthmodeSupported	[%s]\n"),
			//	g_szAuthenticationMode[pCapability->AuthEncryptPair[i].AuthModeSupported]));
			//RETAILMSG(DBG_MSG, (TEXT("	EncryptStatusSupported	[%s]\n"),
			//	g_szcPrivacyMode[pCapability->AuthEncryptPair[i].EncryptStatusSupported]));
		}
	}

	//RETAILMSG(DBG_MSG, (TEXT("rdPMKCache = %u bytes\n"), Intf.rdPMKCache.dwDataLen));

	if (Intf.rdPMKCache.dwDataLen)
	{
		PNDIS_802_11_PMKID	pCache = (PNDIS_802_11_PMKID)Intf.rdPMKCache.pData;
		DWORD i;

		//RETAILMSG(DBG_MSG, (TEXT("  BSSIDInfoCount	:[%u]\n"), pCache->BSSIDInfoCount));

		for (i = 0; i < pCache->BSSIDInfoCount; i++)
		{
			PBYTE pMac = &pCache->BSSIDInfo[i].BSSID[0];
			PBYTE pId = &pCache->BSSIDInfo[i].PMKID[0];
			//RETAILMSG(DBG_MSG, (TEXT("	BSSID=%02X%02X%02X%02X%02X%02X PMKID=%02X%02X..%02X\n"),
			//	pMac[0], pMac[1], pMac[2], pMac[3], pMac[4], pMac[5],
			//	pId[0], pId[1], pId[14], pId[15]));
		}
	}

	// Print WEP status
	if (dwOutFlgs & INTF_WEPSTATUS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WEP Status	= [%d] "), Intf.nWepStatus));

		WCHAR* szWepStatus[] =
		{
			L"Ndis802_11WEPEnabled",
			L"Ndis802_11WEPDisabled",
			L"Ndis802_11WEPKeyAbsent",
			L"Ndis802_11WEPNotSupported"
		};

		if (Intf.nWepStatus < 4)
		{
			//RETAILMSG(DBG_MSG, (TEXT("%s\n"), szWepStatus[Intf.nWepStatus]));
		}
		else
		{
			//RETAILMSG(DBG_MSG, (TEXT("<unkonwn value>\n")));
		}
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("WEP Status	= <unkonwn>\n")));
	}

	//  print SSID status
	if (dwOutFlgs & INTF_SSID)
	{
		//RETAILMSG(DBG_MSG, (TEXT("SSID = ")));
		PrintSSID(&Intf.rdSSID,tSsid);
		//RETAILMSG(DBG_MSG, (TEXT("\n")));
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("SSID = <unkonwn>\n")));
	}


	if (dwOutFlgs & INTF_CAPABILITIES)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Capabilities = \n")));

		if (Intf.dwCapabilities & INTFCAP_SSN)
		{
			//RETAILMSG(DBG_MSG, (TEXT("	WPA/TKIP capable\n")));
		}
		if (Intf.dwCapabilities & INTFCAP_80211I)
		{
			//RETAILMSG(DBG_MSG, (TEXT("	WPA/AES capable\n")));
		}
	}

	//RETAILMSG(DBG_MSG, (TEXT("\n")));
	//RETAILMSG(DBG_MSG, (TEXT("[Availavle Networks] SSID List ")));
	//PrintConfigList(&Intf.rdBSSIDList);

	//RETAILMSG(DBG_MSG, (TEXT("\n")));
	//RETAILMSG(DBG_MSG, (TEXT("[Preferred Networks] SSID List ")));
	//PrintConfigList(&Intf.rdStSSIDList);

	//RETAILMSG(DBG_MSG, (TEXT("\n")));
	//RETAILMSG(DBG_MSG, (TEXT("rdCtrlData length = %d bytes.\n"), Intf.rdCtrlData.dwDataLen));

	//
	//  Free memory block that WFlan allocated
	//  WFlan QueryInterfaceEx() always should be followed by this WZCDeleteIntfObj();
	//  Note that the wzcGuid is ** NOT ** freed by WZCDeleteIntObj()
	//

	WZCDeleteIntfObjEx(&Intf);

	//
	//        Get context information
	//

	//RETAILMSG(DBG_MSG, (TEXT("\n")));
	//RETAILMSG(DBG_MSG, (TEXT("Paramter setting in Zero Config\n")));

	WZC_CONTEXT	WzcContext;

	dwStatus = WZCQueryContext(NULL, 0x00, &WzcContext, NULL);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("!!! Failed WZCQueryContext() Err = [0x%08X] !!!\n"), dwStatus));
	}
	else
	{
		//RETAILMSG(DBG_MSG, (TEXT("tmTr = %d mili-seconds (Scan time out)\n"), WzcContext.tmTr));
		//RETAILMSG(DBG_MSG, (TEXT("tmTp = %d mili-seconds (Association time out)\n"), WzcContext.tmTp));
		//RETAILMSG(DBG_MSG, (TEXT("tmTc = %d mili-seconds (Periodic scan when conected)\n"), WzcContext.tmTc));
		//RETAILMSG(DBG_MSG, (TEXT("tmTf = %d mili-seconds (Periodic scan when disconnected)\n"), WzcContext.tmTf));
	}
}


/************************************************************************/
/*  函数名称:  IsWirelessCard()                                         */
/*  函数作用:  判断是否存在网卡                                         */
/************************************************************************/
BOOL IsWirelessCard(PTCHAR pCard)
{
	if (!pCard)
	{
		return FALSE;
	}

	INTFS_KEY_TABLE IntfsTable;
	IntfsTable.dwNumIntfs = 0;
	IntfsTable.pIntfs = NULL;
	
	DWORD dwStatus = WZCEnumInterfaces(NULL, &IntfsTable);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WZCEnumInterfaces() error 0x%08X\n"),dwStatus));
		return FALSE;
	}

	if (!IntfsTable.dwNumIntfs)
	{
		//RETAILMSG(DBG_MSG, (TEXT("System has no wireless card.\n")));
		return FALSE;
	}

	for (uint i = 0; i < IntfsTable.dwNumIntfs; i++)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WIFI Card [%d] = %s\n"), i, IntfsTable.pIntfs[i].wszGuid));
		if (_tcscmp(pCard, IntfsTable.pIntfs[i].wszGuid) == 0)
		{
			LocalFree(IntfsTable.pIntfs);

            //RETAILMSG(DBG_MSG, (TEXT("Netcard = %s is Wireless Card\n"), pCard));
			return TRUE;
		}
		
	}
	return FALSE;
}

/*************************************************************************/
/*  函数名称:  GetFirstWirelessCard()                                    */
/*  函数作用:  获取第一块无线网卡                                        */
/*             pCard: 无线网卡 GUID                                      */
/*  find the first wireless network cards                                */
/*  found card name goes to g_FirstWirelessCard                          */
/*************************************************************************/
BOOL GetFirstWirelessCard(PTCHAR pCard)
{
	if (!pCard)
	{
		return FALSE;
	}

	INTFS_KEY_TABLE IntfsTable;
	IntfsTable.dwNumIntfs = 0;
	IntfsTable.pIntfs = NULL;

	_tcscpy(pCard, TEXT(""));
	//  权举系统中可用的无线网卡
	DWORD dwStatus = WZCEnumInterfaces(NULL, &IntfsTable);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WZCEnumInterfaces() error 0x%08X\n"),dwStatus));

		return FALSE;
	}
	//  判断无线网卡的数量,可以根据无线网卡数量来权举出所有可用的无线网卡
	//  print the GUIDs
	//  note that in CE the GUIDs are simply the device instance name
	//  i.e XWIFI11B1, CISC01, ISLP2, ...
	//
	if (!IntfsTable.dwNumIntfs)
	{
		//RETAILMSG(DBG_MSG, (TEXT("System has no wireless card.\n")));
		return FALSE;
	}

	_tcscpy(pCard, IntfsTable.pIntfs[0].wszGuid);            //获得第一块网卡的GUID

	//  need to free memory allocated by WZC for us
	LocalFree(IntfsTable.pIntfs);

	return TRUE;
}


/************************************************************************/
/*  函数名称: GetWirelessCardInfo() 获取网卡基本信息                    */
/*  函数作用: pCard: 无线网卡 GUID                                      */
/*     pIntf: 无线网卡配置信息结果体                                    */
/*     pOutFlags: 网卡配置信息掩码标志                                  */
/************************************************************************/

BOOL GetWirelessCardInfo(PTCHAR pCard, PINTF_ENTRY_EX pIntf, PDWORD pOutFlags)
{
	TCHAR *szWiFiCard = NULL;

	// 参数校验
	if (!pCard || !pIntf || !pOutFlags)
	{
		//RETAILMSG(DBG_MSG, (TEXT("Param Error.\n")));
		return FALSE;
	}		

	szWiFiCard = pCard;
	
	*pOutFlags = 0;
	
	// 初始化无线网卡信息
	ZeroMemory(pIntf, sizeof(INTF_ENTRY_EX));
	
	// 设置 GUID 号
	pIntf->wszGuid = szWiFiCard;

	// 查询无线网卡信息
	DWORD dwStatus = WZCQueryInterfaceEx(NULL, INTF_ALL, pIntf, pOutFlags);

	if (dwStatus != ERROR_SUCCESS)
	{
		//RETAILMSG(DBG_MSG, (TEXT("WZCQueryInterfaceEx() error 0x%08X\n"), dwStatus));
		return FALSE;
	}
	
	return TRUE;
}

/************************************************************************/
/*  函数名称: IsAssociated()                                            */
/*  函数作用: 通过网卡的MAC地址来判断关联状态                           */
/************************************************************************/

BOOL IsAssociated(const INTF_ENTRY_EX Intf, const DWORD dwOutFlags)
{	 
	if (dwOutFlags & INTF_BSSID)
	{
		PRAW_DATA prdMAC = (PRAW_DATA)(&Intf.rdBSSID);

	    // 判断 BSSID 的 MAC 地址是否有效来判断是否和无线AP建立了连接 
		if (prdMAC == NULL || prdMAC->dwDataLen == 0 || 
			(!prdMAC->pData[0] && !prdMAC->pData[1] && !prdMAC->pData[2] &&
			!prdMAC->pData[3] && !prdMAC->pData[4] && !prdMAC->pData[5]))
		{
			//g_MainDlg->m_listbox.AddString(L"(This wifi card is not associated to any)");  //关联失败
			return TRUE;
			isconnect = FALSE;
		}
		else
		{
			//g_MainDlg->m_listbox.AddString(L"(This wifi card is associated state)");		//已经关联	
			return FALSE;
		}
	}
	else
	{
		return FALSE;
	}	
}


/************************************************************************************************/
/* 函数名称:GetWirelseeListSSID()                                                               */
/* 函数作用:获取了无线网卡的信息后,                                                            */
/*          可以通过无线网卡枚举出当前所有可用的无线AP的SSID名称以及加密模式等等所有可用信息。  */    
/* 信号强度强弱划分:                                                                           */
/* RSSI    <-90: NO signal                                                                      */
/*         <-81: very low                                                                       */
/*         <-71: low                                                                            */
/*         <-67: Good                                                                           */
/*         <-57: very Good                                                                      */
/*         ... : excellent                                                                      */
/************************************************************************************************/
void CWLanConfig::GetWirelseeListSSID(const PRAW_DATA prdBSSIDList,PRAW_DATA prdSSID,vector<SsidInfo> &SsidList)                     
{
	SsidInfo tempInfo; 

	if (prdSSID == NULL || prdSSID->dwDataLen == 0)
	{
		//RETAILMSG(DBG_MSG, (TEXT("<null>")));
	}
	else
	{
		MultiByteToWideChar(CP_ACP,0,(LPCSTR)prdSSID->pData,-1,tSsid,MAX_PATH*2); 
	}

	if (prdBSSIDList == NULL || prdBSSIDList->dwDataLen  == 0)  
	{  
		return;  
	}  
	else  
	{  
		PWZC_802_11_CONFIG_LIST pConfigList = (PWZC_802_11_CONFIG_LIST)prdBSSIDList->pData;  
	
		int i;  
		// 枚举所有无线AP  
		for (i = 0; i < pConfigList->NumberOfItems; i++)  
		{  
			PWZC_WLAN_CONFIG pConfig = &(pConfigList->Config[i]); 
			RAW_DATA rdBuffer;  
			rdBuffer.dwDataLen = pConfig->Ssid.SsidLength;  
			rdBuffer.pData = pConfig->Ssid.Ssid;  

			// 将 SSID 的 ASCII 码转化成字符串 
			memset(tSsid,0,sizeof(tSsid));	
			PrintSSID(&rdBuffer,tSsid);	
			wcscpy_s(tempInfo.sSsid,MAX_PATH,tSsid);
			tempInfo.nRssi=(int)pConfig->Rssi;
			tempInfo.InfrastructureMode=pConfig->InfrastructureMode;
			tempInfo.AuthenticationMode=pConfig->AuthenticationMode; 
			tempInfo.ulPrivacy=pConfig->Privacy; 

		    tempInfo.ID = i;  //每个ap获取唯一的标识id

			SsidList.push_back(tempInfo);
		}
	}
}
 
/*****************************************************************************************************/
/*   WirelessConnect()  根据上面得到的信息,加上用户输入的密码,生成的信息交给WINDOWS的首选网络列表    */
/*   pCard: 无线网卡 GUID                                                                            */
/*   pSSID: 无线AP SSID号                                                                            */
/*   bAdhoc: 是否点对点的 WIFI 连接                                                                  */
/*   ulPrivacy: 加密模式(WEP/WPA....)                                                                */
/*   ndisMode:  认证模式(Open/Share)                                                                 */
/*   iKeyIndex:  密匙索引                                                                            */
/*   pKey:   密码                                                                                    */
/*   iEapType: 802.11 认证模式                                                                       */
/*   isconnectid:  id标识符区分因SSID相同造成连接不成功问题                                          */                       
/*****************************************************************************************************/
BOOL CWLanConfig::WirelessConnect(PTCHAR pCard, PTCHAR pSSID,NDIS_802_11_NETWORK_INFRASTRUCTURE infr, ULONG ulPrivacy,   NDIS_802_11_AUTHENTICATION_MODE ndisMode, PTCHAR pKey,int iKeyIndex, int iEapType, int isconnectid) 
//pCard: 无线网卡 GUID;pSSID: 无线AP SSID;bAdhoc: 是否点对点的 WIFI 连接;ulPrivacy: 加密模式(WEP/WPA....) ; 
//ndisMode: 认证模式(Open/Share);iKeyIndex: 密钥索引(1-4);pKey: 密码;iEapType: 802.11 认证模式 
{ 
	ResetPreferredList(pCard); //断开函数
	wcscpy(ISSsid,pSSID); //获取ISSsid为连接状态做准备

	BOOL bRet = FALSE;  
	if (!pSSID) 
	{ 
		return FALSE; 
	} 
	else 
	{ 
		WZC_WLAN_CONFIG wzcConfig; 
		ZeroMemory(&wzcConfig, sizeof(WZC_WLAN_CONFIG));  
		wzcConfig.Length = sizeof(WZC_WLAN_CONFIG); 
		wzcConfig.dwCtlFlags = 0; 
		wzcConfig.Ssid.SsidLength = _tcslen(pSSID); 
		for (UINT i = 0; i < wzcConfig.Ssid.SsidLength; i++) 
		{ 
			wzcConfig.Ssid.Ssid[i] = (CHAR)pSSID[i]; 
		} 
		wzcConfig.InfrastructureMode = infr;
		wzcConfig.AuthenticationMode = ndisMode; 
		wzcConfig.Privacy = ulPrivacy; 

		if (pKey == NULL || _tcslen(pKey) == 0) 
		{ 
			// 对密钥进行转换 
			bRet = InterpretEncryptionKeyValue(wzcConfig, 0, NULL, TRUE); 
			wzcConfig.EapolParams.dwEapType = iEapType;
			wzcConfig.EapolParams.dwEapType =EAP_TYPE_TLS;
			wzcConfig.EapolParams.dwEapFlags = EAPOL_ENABLED; 
			wzcConfig.EapolParams.bEnable8021x  = TRUE; 
			wzcConfig.EapolParams.dwAuthDataLen = 0; 
			wzcConfig.EapolParams.pbAuthData = 0; 
		} 
		else 
		{ 
			//RETAILMSG(DBG_MSG, (TEXT("WirelessConnect iKeyIndex = %d.\n"), iKeyIndex));    	    
			bRet = InterpretEncryptionKeyValue(wzcConfig, iKeyIndex, pKey, FALSE); 
		} 
		
		// 连接到指定的无线AP,并将该AP添加到首先无线AP中 
		AddToPreferredNetworkList(pCard, wzcConfig, pSSID); 
		
	} 
	return bRet; 
}  

/***************************************************************************/
/*  函数名称: AddToPreferredNetworkList()                                  */
/*  函数作用: 把用户获取的SSID加入WINDOWS的首选                            */
/*            adding to the [Preferred Networks]                           */
/*            [Preferred Networks] is a list of SSIDs in preference order. */
/*            WZC continuously scans available SSIDs and attempt to        */
/*            connect to the most preferable SSID.                         */
/***************************************************************************/
void CWLanConfig::AddToPreferredNetworkList
(
 IN WCHAR *szWiFiCard,
 IN WZC_WLAN_CONFIG& wzcConfig1,
 IN WCHAR *szSsidToConnect
 )
{
	DWORD dwOutFlags = 0;
	INTF_ENTRY_EX Intf;
	memset(&Intf, 0x00, sizeof(INTF_ENTRY_EX));
	Intf.wszGuid = szWiFiCard;

	DWORD dwStatus = WZCQueryInterfaceEx(
		NULL,
		INTF_ALL,
		&Intf,
		&dwOutFlags);
	if(dwStatus)
	{
		//wprintf(L"WZCQueryInterfaceEx() error dwStatus=0x%0X, dwOutFlags=0x%0X", dwStatus, dwOutFlags);
		WZCDeleteIntfObjEx(&Intf);
		return;
	}

	WZC_802_11_CONFIG_LIST *pConfigList = (PWZC_802_11_CONFIG_LIST)Intf.rdStSSIDList.pData;
	if(!pConfigList)   // empty [Preferred Networks] list case
	{
		DWORD dwDataLen = sizeof(WZC_802_11_CONFIG_LIST);
		WZC_802_11_CONFIG_LIST *pNewConfigList = (WZC_802_11_CONFIG_LIST *)LocalAlloc(LPTR, dwDataLen);
		pNewConfigList->NumberOfItems = 1;
		pNewConfigList->Index = 0;
		memcpy(pNewConfigList->Config, &wzcConfig1, sizeof(wzcConfig1));
		Intf.rdStSSIDList.pData = (BYTE*)pNewConfigList;
		Intf.rdStSSIDList.dwDataLen = dwDataLen;
	}
	else
	{
		ULONG uiNumberOfItems = pConfigList->NumberOfItems;
		for(UINT i=0; i<uiNumberOfItems; i++)
		{
			if(memcmp(&wzcConfig1.Ssid, &pConfigList->Config[i].Ssid, sizeof(NDIS_802_11_SSID)) == 0)
			{
				//wprintf(L"%s is already in the [Preferred Networks] list", szSsidToConnect);
				WZCDeleteIntfObjEx(&Intf);
				return;
			}
		}
	
		//wprintf(L"SSID List has [%d] entries.\n", uiNumberOfItems);
		
        //连接状态显示
		//wprintf(L"adding %s to the top of [Preferred Networks]\n", szSsidToConnect);                // this will be the most preferable SSID

		DWORD dwDataLen = sizeof(WZC_802_11_CONFIG_LIST) + (uiNumberOfItems+1)*sizeof(WZC_WLAN_CONFIG);
		WZC_802_11_CONFIG_LIST *pNewConfigList = (WZC_802_11_CONFIG_LIST *)LocalAlloc(LPTR, dwDataLen);
		pNewConfigList->NumberOfItems = uiNumberOfItems + 1;
		pNewConfigList->Index = 0;

		memcpy(pNewConfigList->Config, &wzcConfig1, sizeof(wzcConfig1));
		if(pConfigList->NumberOfItems)
		{
			pNewConfigList->Index = pConfigList->Index;
			memcpy(pNewConfigList->Config+1, pConfigList->Config, (uiNumberOfItems)*sizeof(WZC_WLAN_CONFIG));
			LocalFree(pConfigList);
			pConfigList = NULL;
		}

		Intf.rdStSSIDList.pData = (BYTE*)pNewConfigList;
		Intf.rdStSSIDList.dwDataLen = dwDataLen;
	}

	dwStatus = WZCSetInterfaceEx(NULL, INTF_PREFLIST, &Intf, &dwOutFlags);
	if(dwStatus)
	{
		//wprintf(L"WZCSetInterfaceEx() error dwStatus=0x%0X, dwOutFlags=0x%0X", dwStatus, dwOutFlags);
	}

	WZCDeleteIntfObjEx(&Intf);
}   // AddToPreferredNetworkList()

/************************************************************************/
/*  函数名称: EncryptWepKMaterial()                                       */
/*  函数作用: 密码加密算法                                                 */
/*  输入的密匙需要通过加密方式进行一定的转化,以下函数可以完成改功能              */
/************************************************************************/

static void EncryptWepKMaterial(IN OUT WZC_WLAN_CONFIG* pwzcConfig)  
{  
	BYTE chFakeKeyMaterial[] = { 0x56, 0x09, 0x08, 0x98, 0x4D, 0x08, 0x11, 0x66, 0x42, 0x03, 0x01, 0x67, 0x66 };  
	for (int i = 0; i < WZCCTL_MAX_WEPK_MATERIAL; i++)  
	{
		pwzcConfig->KeyMaterial[i] ^= chFakeKeyMaterial[(7*i)%13];  
	}
}  


/************************************************************************/
/*   函数名称: IsWifiConnected()                                         */
/*   函数作用: 判断网卡是否连接到无线网络的状态                               */
/************************************************************************/
int IsWifiConnected(PTCHAR pCard,const INTF_ENTRY_EX Intf)  
{
	mFlag = 0;
	PRAW_DATA prdMAC = (PRAW_DATA)(&Intf.rdBSSID);

	// 判断 BSSID 的 MAC 地址是否有效来判断是否和无线AP建立了连接 
	if (prdMAC == NULL || prdMAC->dwDataLen == 0 || 
		(!prdMAC->pData[0] && !prdMAC->pData[1] && !prdMAC->pData[2] &&
		!prdMAC->pData[3] && !prdMAC->pData[4] && !prdMAC->pData[5]))
	{
	    //g_MainDlg->m_State.SetWindowText(L"关联失败");
		mFlag = 1;
		isconnect = FALSE;               //连接失败标识符
		//return bHasDefaultRoute;
	}
	else
	{
		//BOOL bHasDefaultRoute = FALSE;
		ULONG wifiindex =0; 
		if(NO_ERROR == GetAdapterIndex(pCard,&wifiindex))  
		{  
			DWORD dwTableSize = 0;  
			GetIpAddrTable(NULL, &dwTableSize, FALSE);  
			if (dwTableSize)  
			{  
				MIB_IPADDRTABLE* pft;  
				pft = (MIB_IPADDRTABLE*)malloc(dwTableSize);  
				if (pft)  
				{  
					if (GetIpAddrTable(pft, &dwTableSize, TRUE) == NO_ERROR)  
					{   
						for (ulong nIndex = 0; nIndex < pft->dwNumEntries; nIndex++)  
						{  
							if (pft->table[nIndex].dwIndex == wifiindex)  
							{  
								//printf("get wifi index\n");  
								//printf("wifi add = %x\n",pft->table[nIndex].dwAddr);  
								if (0!=pft->table[nIndex].dwAddr)  
								{  
								    isconnect = TRUE;               //显示连接成功符号
									mFlag = 2;
									//bHasDefaultRoute = TRUE;    
									//return bHasDefaultRoute;  
								}  
								break;  
							}  
						}  
					}  
					free(pft);  
				}  
			}  
		}  
		//return bHasDefaultRoute;  
	}
	return mFlag;
} 






已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页