Example #1
0
static void WlanOpenHandle_test(void)
{
    DWORD ret;
    DWORD dwNegotiatedVersion;
    HANDLE hClientHandle;

    /* correct call to determine if WlanSvc is running */
    ret = WlanOpenHandle(1, NULL, &dwNegotiatedVersion, &hClientHandle);
    if (ret == ERROR_SERVICE_EXISTS)
    {
        skip("Skipping wlanapi tests, WlanSvc is not running\n");
        return;
    }
    ok(ret == ERROR_SUCCESS, "WlanOpenHandle failed, error %ld\n", ret);
    WlanCloseHandle(hClientHandle, NULL);

    /* invalid pdwNegotiatedVersion */
    ret = WlanOpenHandle(1, NULL, NULL, &hClientHandle);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());

    /* invalid hClientHandle */
    ret = WlanOpenHandle(1, NULL, &dwNegotiatedVersion, NULL);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());

    /* invalid pReserved */
    ret = WlanOpenHandle(1, (PVOID) 1, &dwNegotiatedVersion, &hClientHandle);
    ok(ret == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %ld\n", GetLastError());
}
Example #2
0
void								wififriend_scan_network(GtkWidget* Widget, gpointer Data)
{
	DWORD							Error = ERROR_SUCCESS;
	PWLAN_AVAILABLE_NETWORK_LIST	Network = NULL;
	t_wifi							St;
	int								I;
	GtkWidget						*WinScan = NULL;
	GtkWidget						*ListOfWifi = NULL;

	I = 1;
	St = wififriend_create_handle();
	St = wififriend_retrieve_config(St);
	if((WlanGetAvailableNetworkList(St.MyHandle, &St.MyGuid, 0x00000001, NULL, &Network)) != ERROR_SUCCESS)
		error_scan(0);
	else
	{
		WinScan = create_window(236, 27, "Wifi scan");
		ListOfWifi = gtk_combo_box_new_text();
		while(I != Network->dwNumberOfItems)
		{
			gtk_combo_box_prepend_text(GTK_COMBO_BOX(ListOfWifi), (const gchar *)Network->Network[I].dot11Ssid.ucSSID);
			I++;
		}
		gtk_combo_box_set_active(GTK_COMBO_BOX(ListOfWifi), 0);
		gtk_container_add(GTK_CONTAINER(WinScan), ListOfWifi);
		g_signal_connect(G_OBJECT(ListOfWifi), "changed", G_CALLBACK(wififriend_connect_to_unsecure_network), (gpointer)ListOfWifi);
		display_interface(WinScan);
		WlanCloseHandle(St.MyHandle, NULL);
	}
}
Example #3
0
void Wlan::CloseHandle()
{
    if (m_handle != NULL) {
        WlanCloseHandle( m_handle, NULL );
        m_handle = NULL;
    }
}
Example #4
0
/*
 * Get the index of the first available network in the list
 */
DWORD GetWlanAvailableSSID (WLANKEY *keys,
                            int *index,
                            WLAN_REASON_CODE *reason){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	wchar_t *ifname;
	unsigned int i;
	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	*index = -1;
	for (i=0; *index == -1 && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		ifname = iflist->InterfaceInfo[i].strInterfaceDescription;
		status = GetIfaceAvailableSSID (h, iface, ifname, keys, index, reason);
	}
	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
Example #5
0
static void WlanCloseHandle_test(void)
{
    DWORD ret;
    HANDLE hClientHandle = (HANDLE) 0xdeadbeef;

    /* invalid pReserved */
    ret = WlanCloseHandle(hClientHandle, (PVOID) 1);
    ok(ret == ERROR_INVALID_PARAMETER, "expected failure\n");

    /* invalid hClientHandle */
    ret = WlanCloseHandle(NULL, NULL);
    ok(ret == ERROR_INVALID_PARAMETER, "expected failure\n");

    /* invalid hClientHandle */
    ret = WlanCloseHandle(hClientHandle, NULL);
    ok(ret == ERROR_INVALID_HANDLE, "expected failure\n");
}
Example #6
0
void KPR_system_getWifiInfo(xsMachine* the)
{
    DWORD dwResult = 0;
    HANDLE hClient = NULL;
    DWORD dwMaxClient = 2; 
    DWORD dwCurVersion = 0;
    PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
    int i;
    PWLAN_INTERFACE_INFO pIfInfo = NULL;
    DWORD connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);
    PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;
    WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;
    ULONG length;
	xsVars(1);
    dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); 
    if (dwResult != ERROR_SUCCESS) 
    	goto bail;
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList); 
    if (dwResult != ERROR_SUCCESS)
    	goto bail;
    for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) {
		pIfInfo = (WLAN_INTERFACE_INFO *) &pIfList->InterfaceInfo[i];
   		if (pIfInfo->isState == wlan_interface_state_connected) {
			dwResult = WlanQueryInterface(hClient, &pIfInfo->InterfaceGuid,
										  wlan_intf_opcode_current_connection,
										  NULL,
										  &connectInfoSize,
										  (PVOID *) &pConnectInfo, 
										  &opCode);
			if (dwResult != ERROR_SUCCESS)
				goto bail;
			length = pConnectInfo->wlanAssociationAttributes.dot11Ssid.uSSIDLength;
			if (length > 0) {
				xsResult = xsNewInstanceOf(xsObjectPrototype);
				xsVar(0) = xsStringBuffer(NULL, length + 1);
				FskMemCopy(xsToString(xsVar(0)), pConnectInfo->wlanAssociationAttributes.dot11Ssid.ucSSID, length);
				xsSet(xsResult, xsID("SSID"), xsVar(0));
			}
   			break;
   		}
   	}
bail:
    if (pConnectInfo != NULL) {
        WlanFreeMemory(pConnectInfo);
        pConnectInfo = NULL;
    }
    if (pIfList != NULL) {
        WlanFreeMemory(pIfList);
        pIfList = NULL;
    }
    if (hClient != NULL) {
        WlanCloseHandle(hClient, NULL);
        hClient = NULL;
    }
}
Example #7
0
void		wififriend_disconnect_user(GtkWidget* Widget, gpointer Data)
{
	t_wifi	Disconnect;

	Disconnect = wififriend_create_handle();
	Disconnect = wififriend_retrieve_config(Disconnect);
	if ((WlanDisconnect(Disconnect.MyHandle, &Disconnect.MyGuid, NULL)!= ERROR_SUCCESS))
		error_cannot_disconnect(0);
	else
		error_disconnect_success(0);
	WlanCloseHandle(Disconnect.MyHandle, NULL);
}
Example #8
0
void SetProfile( GUID guidIntf, char *essid, char *pwd )
{
	DWORD dwError;
	HANDLE hClient = NULL;
	DWORD dwReason;

	wchar_t strXml[1024];
	_snwprintf( strXml, _countof(strXml), szProfileStringFmt, essid, essid, pwd );

	// open handle
	if ((dwError = OpenHandleAndCheckVersion(
		&hClient
		)) != ERROR_SUCCESS)
	{
		puts( "error open handle" );
		return;
	}

	// set profile
	dwError = WlanSetProfile(
		hClient, 
		&guidIntf, 
		0,          // no flags for the profile 
		strXml, 
		NULL,       // use the default ACL
		TRUE,		// overwrite a profile if it already exists
		NULL,       // reserved
		&dwReason
		);

	switch(dwError)
	{
	case ERROR_INVALID_PARAMETER:
		puts( "The profile has invalid params." );
		break;
	case ERROR_BAD_PROFILE:
		puts( "The profile is bad." );
		break;
	case ERROR_ALREADY_EXISTS:
		puts( "The profile is already exists." );
	}

	// clean up
	if (hClient != NULL)
	{
		WlanCloseHandle(
			hClient, 
			NULL            // reserved
			);
	}
}
Example #9
0
DWORD SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}
Example #10
0
// open a WLAN client handle and check version
DWORD
OpenHandleAndCheckVersion(
						  PHANDLE phClient
						  )
{
	DWORD dwError = ERROR_SUCCESS;
	DWORD dwServiceVersion;
	HANDLE hClient = NULL;

	__try
	{
		*phClient = NULL;

		// open a handle to the service
		if ((dwError = WlanOpenHandle(
			WLAN_API_VERSION,
			NULL,               // reserved
			&dwServiceVersion,
			&hClient
			)) != ERROR_SUCCESS)
		{
			__leave;
		}

		// check service version
		if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
		{
			// No-op, because the version check is for demonstration purpose only.
			// You can add your own logic here.
		}

		*phClient = hClient;

		// set hClient to NULL so it will not be closed
		hClient = NULL;
	}
	__finally
	{
		if (hClient != NULL)
		{
			// clean up
			WlanCloseHandle(
				hClient, 
				NULL            // reserved
				);
		}
	}

	return dwError;
}
Example #11
0
DWORD GetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)
{
	DWORD dwResult = 0;
	HANDLE hClient = NULL;
	DWORD dwCurVersion = 0;
	DWORD outsize = 0;
	WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_invalid;

	// Open Handle for the set operation
	dwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);
	dwResult = WlanQueryInterface(hClient, InterfaceGuid, opcode, NULL, &outsize, pData, &opCode);
	WlanCloseHandle(hClient, NULL);

	return dwResult;
}
Example #12
0
void FinalizeHandle()
{
	g_pInterface = nullptr;

	if (g_pIntfList != nullptr)
	{
		WlanFreeMemory(g_pIntfList);
		g_pIntfList = nullptr;
	}

	if (g_hClient != nullptr)
	{
		WlanCloseHandle(g_hClient, nullptr);
		g_hClient = nullptr;
	}
}
Example #13
0
void								wififriend_display_wifi_params(GtkWidget* Widget, gpointer Data)
{
	int								I = 0;
	PWLAN_INTERFACE_INFO_LIST		InterfaceList = NULL;
	t_wifi							St;
	GtkWidget						*Win = NULL;
	GtkWidget						*Vbox;
	GtkWidget						*NbInterface = NULL;
	GtkWidget						*NbInterfaceResult = NULL;
	GtkWidget						*Guid = NULL;
	GtkWidget						*GuidResult = NULL;
	GtkWidget						*State = NULL;
	GtkWidget						*StateResult = NULL;
	GtkWidget						*Description = NULL;
	GtkWidget						*DescriptionResult = NULL;
	gchar							*String = NULL;

	St = wififriend_create_handle();
	St = wififriend_retrieve_config(St);
	Win = create_window(300, 180, "Configuration Wifi");
	Vbox = gtk_vbox_new(FALSE, 0);
	if ((WlanEnumInterfaces(St.MyHandle, NULL, &InterfaceList)) != ERROR_SUCCESS)
		error_interface_wifi(0);
	else
	{
		NbInterface = gtk_label_new("- Nombre d'interface Wifi trouvee: ");
		gtk_box_pack_start(GTK_BOX(Vbox), NbInterface, FALSE, FALSE, 0);
		String = g_strdup_printf ("%d", InterfaceList->dwNumberOfItems);
		NbInterfaceResult = gtk_label_new(String);
		gtk_box_pack_start(GTK_BOX(Vbox), NbInterfaceResult, FALSE, FALSE, 2);
		Guid = gtk_label_new("- GUID de votre interface Wifi: ");
		gtk_box_pack_start(GTK_BOX(Vbox), Guid, FALSE, FALSE, 5);
		String = g_strdup_printf ("%d", InterfaceList->InterfaceInfo->InterfaceGuid);
		GuidResult = gtk_label_new(String);
		gtk_box_pack_start(GTK_BOX(Vbox), GuidResult, FALSE, FALSE, 2);
		State = gtk_label_new("- Etat de l'interface: ");
		gtk_box_pack_start(GTK_BOX(Vbox), State, FALSE, FALSE, 5);
		String = g_strdup_printf ("%d", InterfaceList->InterfaceInfo->isState);
		StateResult = gtk_label_new(String);
		gtk_box_pack_start(GTK_BOX(Vbox), StateResult, FALSE, FALSE, 2);
		gtk_container_add(GTK_CONTAINER(Win), Vbox);
		display_interface(Win);
		WlanCloseHandle(St.MyHandle, NULL);
	}
}
CWlanManager::~CWlanManager()
{
    // Unadvise, ignore the error
    UnadviseHostedNetworkNotification();

    if (m_WlanHandle != NULL)
    {
        WlanCloseHandle(m_WlanHandle, NULL);
        m_WlanHandle = NULL;
    }
    
    if (m_CallbackComplete != NULL)
    {
        CloseHandle(m_CallbackComplete);
        m_CallbackComplete = NULL;
    }

    DeleteCriticalSection(&m_CriticalSection);
}
Example #15
0
void							wififriend_connect_to_unsecure_network(GtkWidget* Widget, gpointer Data)
{
	t_wifi						Unsecure;
	DWORD						Error = ERROR_SUCCESS;
	WLAN_CONNECTION_PARAMETERS	Connect;

	Unsecure = wififriend_create_handle();
	Unsecure = wififriend_retrieve_config(Unsecure);
	memset(&Connect, 0, sizeof(WLAN_CONNECTION_PARAMETERS));
	Connect.wlanConnectionMode = wlan_connection_mode_discovery_unsecure;
	Connect.strProfile = NULL;
	Connect.pDot11Ssid = NULL;
	Connect.pDesiredBssidList = 0;
	Connect.dot11BssType = dot11_BSS_type_infrastructure;
	Connect.dwFlags = WLAN_CONNECTION_IGNORE_PRIVACY_BIT;
	if((Error = WlanConnect(Unsecure.MyHandle, &Unsecure.MyGuid, &Connect, NULL)) != ERROR_SUCCESS)
		error_unauthorized_connect(0);
	WlanCloseHandle(Unsecure.MyHandle, NULL);
}
Example #16
0
void			wififriend_extract_next(GtkWidget* Widget, gpointer Data)
{
	DWORD		Error = ERROR_SUCCESS;
	GtkWidget	*Profil;
	t_wifi		Extract;
	const gchar	*Retrieve;
	long		Size;
	BSTR		UnicodeStr;
	LPWSTR		OutProfil;
	char		*NewProfil;
	FILE		*File;
	int			I = 0;
	char		*PathFile;

	Profil = (GtkWidget *)Data;
	Retrieve = gtk_entry_get_text(GTK_ENTRY(Profil));
	Extract = wififriend_create_handle();
	Extract = wififriend_retrieve_config(Extract);
	Size = lstrlenA(Retrieve);
	UnicodeStr = SysAllocStringLen(NULL, Size);
	MultiByteToWideChar(CP_ACP, 0, Retrieve, Size, UnicodeStr, Size);
	if((Error = WlanGetProfile(Extract.MyHandle, &Extract.MyGuid, UnicodeStr, NULL, &OutProfil, 0, 0)) != ERROR_SUCCESS)
		error_get_profil(0, Retrieve);
	else
	{
		while (OutProfil[I])
			I++;
		NewProfil = (char *)malloc(sizeof(char) * I + 1);
		wcstombs(NewProfil, OutProfil, I + 1);
		PathFile = (char *)malloc(sizeof(char *) * strlen(Retrieve) + 1);
		strcpy(PathFile, Retrieve);
		strcat(PathFile, ".xml");
		File = fopen(PathFile, "w+");
		fputs(NewProfil, File);
		fclose(File);
		free(PathFile);
		error_get_profil_success(0, Retrieve);
	}
	SysFreeString(UnicodeStr);
	WlanCloseHandle(Extract.MyHandle, NULL);
}
Example #17
0
/*!
 *  \fn DWORD PMD::cleanup()
 *  \ingroup win32backend
 *  \private
 *  \brief Cleans up the allocated memory before exiting a function.
 */
VOID PMD::cleanup() {

	if (hClientHandle != NULL) {
		printf ("\thClientHandle not null\n");
        WlanCloseHandle(
			hClientHandle, 
			NULL            // reserved
		);
    }
	if (pInterfaceList != NULL) {
		printf ("\tpInterfaceList not null \n");
		WlanFreeMemory(pInterfaceList);
	}
	
	if (pCurrentConnInfo != NULL)
	{
		printf ("\tpCurrentConnInfo not null\n");
		WlanFreeMemory(pCurrentConnInfo);
	}/*
	*/
}
Example #18
0
/*
 * Reorders profiles on all interfaces
 */
DWORD ReorderWlanProfiles (WLANKEY *keys){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	wchar_t *ifname;
	unsigned int i;
	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	for (i=0; status == ERROR_SUCCESS && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		ifname = iflist->InterfaceInfo[i].strInterfaceDescription;
		status = ReorderIfaceProfiles (h, iface, ifname, keys);
	}
	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
Example #19
0
/*
 * Removes existing profiles on all interfaces
 */
DWORD RemoveWlanProfiles (const WLANKEY *profiles,
                          const WLANKEY *keep){
	DWORD apiver;
	DWORD status;
	HANDLE h;
	WLAN_INTERFACE_INFO_LIST *iflist;
	GUID *iface;
	int i;

	status = WlanOpenHandle (1, NULL, &apiver, &h);
	if (status != ERROR_SUCCESS){
		return status;
	}
	status = WlanEnumInterfaces (h, NULL, &iflist);
	for (i=0; status == ERROR_SUCCESS && i < iflist->dwNumberOfItems; i++){
		iface = &(iflist->InterfaceInfo[i].InterfaceGuid);
		status = RemoveIfaceProfiles (h, iface, profiles, keep);
	}

	WlanFreeMemory (iflist);
	WlanCloseHandle (h, NULL);
	return status;
}
Example #20
0
int								wififriend_connect_secure_network(HANDLE Handle, const GUID *Id, char *Strxml)
{
	DWORD						Error = ERROR_SUCCESS;
	WLAN_CONNECTION_PARAMETERS	Connect;
	int							Size;
	BSTR						UnicodeStr;

	memset(&Connect, 0, sizeof(WLAN_CONNECTION_PARAMETERS));
	Connect.wlanConnectionMode = wlan_connection_mode_profile;
	Size = lstrlenA(Strxml);
	UnicodeStr = SysAllocStringLen(NULL, Size);
	MultiByteToWideChar(CP_ACP, 0, Strxml, Size, UnicodeStr, Size);
	Connect.strProfile = UnicodeStr;
	Connect.pDot11Ssid = NULL;
	Connect.pDesiredBssidList = NULL;
	Connect.dot11BssType = dot11_BSS_type_any;
	Connect.dwFlags = 0;
	if ((Error = WlanConnect(Handle, Id, &Connect, NULL)) != ERROR_SUCCESS)
		switch(Error)
		{
			case ERROR_INVALID_HANDLE:
			error_invalid_handle(0);
			break;
			case ERROR_ACCESS_DENIED:
			error_unauthorized_connect(0);
			break;
			case ERROR_INVALID_PARAMETER:
			error_parameters_connect(0);
			break;
			default: 
				error_connect_unknow(0);
		}
	else
		error_connect_success(0, (char *)UnicodeStr);
	WlanCloseHandle(Handle, NULL);
	return (0);
}
Example #21
0
WiFiInfo::Impl::~Impl()
{
  WlanCloseHandle(m_hClient, NULL);
}
Example #22
0
void winstd::wlan_handle::free_internal()
{
    WlanCloseHandle(m_h, NULL);
}
Example #23
0
int TestWlanApi(int argc, _TCHAR* argv[])
{
	// init_lib( &cs );
	// return 0;
	HANDLE hClient = NULL;
	WLAN_INTERFACE_INFO sInfo[64];
	RPC_CSTR strGuid = NULL;

	TCHAR szBuffer[256];
	DWORD dwRead;
	if( OpenHandleAndCheckVersion( &hClient ) != ERROR_SUCCESS )
		return -1;

	UINT nCount = EnumInterface( hClient, sInfo );
	for( UINT i = 0; i < nCount; ++i )
	{
		if (UuidToStringA( &sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)
		{
			printf( ("%d. %s\n\tDescription: %S\n\tState: %S\n"), 
				i, 
				strGuid, 
				sInfo[i].strInterfaceDescription, 
				GetInterfaceStateString(sInfo[i].isState) );

			RpcStringFreeA(&strGuid);
		}
	}

	UINT nChoice = 0;
	printf( "for choice wireless card:" );

	if( ReadConsole( GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL ) == FALSE )
	{
		puts( "error input" );
		return -1;
	}
	szBuffer[dwRead] = 0;
	nChoice = _ttoi( szBuffer );

	if( nChoice > nCount )
	{
		puts( "error input." );
		return -1;
	}

	ULONG ulOperatorCode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	if( ERROR_SUCCESS != WlanSetInterface( 
		hClient, 
		&sInfo[nChoice].InterfaceGuid, 
		wlan_intf_opcode_current_operation_mode,
		sizeof(ULONG),
		&ulOperatorCode,
		NULL ) )
	{
		puts( "enter monitor mode failed!" );
		return -1;
	}

	BOOL bRet = ReadFile( hClient, szBuffer, sizeof(szBuffer), &dwRead, NULL );

	_getch();
	ulOperatorCode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	if( ERROR_SUCCESS != WlanSetInterface( 
		hClient, 
		&sInfo[nChoice].InterfaceGuid, 
		wlan_intf_opcode_current_operation_mode,
		sizeof(ULONG),
		&ulOperatorCode,
		NULL ) )
	{
		puts( "enter monitor mode failed!" );
		return -1;
	}

	WlanCloseHandle( hClient, NULL );
	return 0;
}
Example #24
0
int _tmain(int argc, _TCHAR* argv[])
{
	bool first_run=true;
	DWORD dwRetVal = 0;
	while(1)
	{
	/*Test per funzione di errore*/
	std::map<std::string, int> lMacAddress_TEST;
	
	// Declare and initialize variables.

    HANDLE hClient = NULL;		//Handle del client utilizzato nella sessione corrente
    DWORD dwMaxClient = 2;      //E' una costante che va inserita in WlanOpenHandle (1->Win XP SP2/3 | 2->Win Vista/Server 2008)    
    DWORD dwCurVersion = 0;		//Versione della WLAN API attualmente utilizzata da inserire nella WlanOpenHandle
    DWORD dwResult = 0;
    
    int iRet = 0;
    
    WCHAR GuidString[39] = {0};		//Conterrà un GUID sottoforma di stringa di caratteri

    unsigned int i, j, k;

    /* variables used for WlanEnumInterfaces  */

    PWLAN_INTERFACE_INFO_LIST pIfList = NULL;	//Contiene un array di NIC con relative informazioni
    PWLAN_INTERFACE_INFO pIfInfo = NULL;		//Contiene le informazioni relative ad una NIC (ID, Descrizione, Stato)

    PWLAN_AVAILABLE_NETWORK_LIST pBssList = NULL;	//Contiene un array di reti con relative informazioni
    PWLAN_AVAILABLE_NETWORK pBssEntry = NULL;		//Contiene info relative ad una rete raggiungibile (es. SSID, qualità segnale, algoritmo cifratura)
    
    int iRSSI = 0;

    dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient); //Apre una connessione con il server
    if (dwResult != ERROR_SUCCESS)
		{
        wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
        return 1;
        // You can use FormatMessage here to find out why the function failed
		}

    dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList); //Inserisce in pIfList l'elenco delle NIC abilitate sul pc
    if (dwResult != ERROR_SUCCESS) 
		{
        wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
        return 1;
        // You can use FormatMessage here to find out why the function failed
		} 
	else 
		{
        wprintf(L"Num Entries: %lu\n", pIfList->dwNumberOfItems); //Numero NIC trovate
        wprintf(L"Current Index: %lu\n", pIfList->dwIndex);	//Indice NIC corrente
        for (i = 0; i < (int) pIfList->dwNumberOfItems; i++) 
			{
            pIfInfo = (WLAN_INTERFACE_INFO *) &pIfList->InterfaceInfo[i]; //pIfInfo punta alla struttura con le informazioni relative alla NIC corrente
            wprintf(L"  Interface Index[%u]:\t %lu\n", i, i);
            iRet = StringFromGUID2(pIfInfo->InterfaceGuid, (LPOLESTR) &GuidString,	//Trasforma un GUID in stringa di caratteri 
                sizeof(GuidString)/sizeof(*GuidString));  //Numero di caratteri massimo per la stringa finale
            // For c rather than C++ source code, the above line needs to be
            // iRet = StringFromGUID2(&pIfInfo->InterfaceGuid, (LPOLESTR) &GuidString, 
            //     sizeof(GuidString)/sizeof(*GuidString)); 
            if (iRet == 0)	//Se StringFromGUID2 fallisce ritorna 0
                wprintf(L"StringFromGUID2 failed\n");
            else 
				{		//Altrimenti il numero di caratteri della stringa 
                wprintf(L"  InterfaceGUID[%d]: %ws\n",i, GuidString);
				}    
            wprintf(L"  Interface Description[%d]: %ws", i, pIfInfo->strInterfaceDescription);
            wprintf(L"\n");
            wprintf(L"  Interface State[%d]:\t ", i);
            switch (pIfInfo->isState) 
				{
				case wlan_interface_state_not_ready:
					wprintf(L"Not ready\n");
					break;
				case wlan_interface_state_connected:
					wprintf(L"Connected\n");
					break;
				case wlan_interface_state_ad_hoc_network_formed:
					wprintf(L"First node in a ad hoc network\n");
					break;
				case wlan_interface_state_disconnecting:
					wprintf(L"Disconnecting\n");
					break;
				case wlan_interface_state_disconnected:
					wprintf(L"Not connected\n");
					break;
				case wlan_interface_state_associating:
					wprintf(L"Attempting to associate with a network\n");
					break;
				case wlan_interface_state_discovering:
					wprintf(L"Auto configuration is discovering settings for the network\n");
					break;
				case wlan_interface_state_authenticating:
					wprintf(L"In process of authenticating\n");
					break;
				default:
					wprintf(L"Unknown state %ld\n", pIfInfo->isState);
					break;
				}
            wprintf(L"\n");

			//Inserisce in pBssList i dati delle reti disponibili
            dwResult = WlanGetAvailableNetworkList(hClient,		//Client handle ottenuto all'inizio
                                             &pIfInfo->InterfaceGuid,	//Interface GUID
                                             0, 
                                             NULL, 
                                             &pBssList);	//Puntatore alla lista delle entry trovate

            if (dwResult != ERROR_SUCCESS) 
				{
                wprintf(L"WlanGetAvailableNetworkList failed with error: %u\n", dwResult);
                dwRetVal = 1;
                // You can use FormatMessage to find out why the function failed
				} 
			else 
				{
                wprintf(L"WLAN_AVAILABLE_NETWORK_LIST for this interface\n");

                wprintf(L"  Num Entries: %lu\n\n", pBssList->dwNumberOfItems);

                for (j = 0; j < pBssList->dwNumberOfItems; j++) 
					{
                    pBssEntry = (WLAN_AVAILABLE_NETWORK *) & pBssList->Network[j]; //pBssEntry punta alla struttura di informazioni relative alla rete corrente
                    wprintf(L"  Profile Name[%u]:  %ws\n", j, pBssEntry->strProfileName);
                    wprintf(L"  SSID[%u]:\t\t ", j);
                    if (pBssEntry->dot11Ssid.uSSIDLength == 0) //Se l'SSID ha lunghezza nulla va a capo
                        wprintf(L"\n");
                    else 
						{   
                        for (k = 0; k < pBssEntry->dot11Ssid.uSSIDLength; k++) 
							{
                            wprintf(L"%c", (int) pBssEntry->dot11Ssid.ucSSID[k]); //Scrittura a video dell SSID
							}
                        wprintf(L"\n");
						}
					
					//Prova per ottenere il MAC Address-----------------------------------------------
					//--------------------------------------------------------------------------------
					PWLAN_BSS_LIST pWlanBssList=NULL;
					DWORD uscita=0;
					DOT11_SSID Dot11Ssid=pBssEntry->dot11Ssid;
					
					WlanGetNetworkBssList(
						hClient,		//Client inizializzato precedentemente
						&(pIfInfo->InterfaceGuid),	//Interfaccia sul quale si fanno le misurazioni
						&(pBssEntry->dot11Ssid),	//Struttura del SSID correntemente analizzato
						dot11_BSS_type_infrastructure, //Cerca tra le interfacce di infrastruttura
						pBssEntry->bSecurityEnabled,	//Security policy dell'interfaccia corrente
						NULL,	//DEVE ESSERE NULL
						&pWlanBssList	//Struttura che sarà riempita con info opportune
						);
					if(uscita==ERROR_SUCCESS)
					wprintf(L"\n  GOOD Exit status Bss\n");
					wprintf(L"\n  Number of Bss entries: %u\n", pWlanBssList->dwNumberOfItems);
					//for(int z=0; z<(int)pWlanBssList->dwNumberOfItems;z++)
					//{
						PWLAN_BSS_ENTRY px = (WLAN_BSS_ENTRY *) & pWlanBssList->wlanBssEntries;
						std::string sMACAddress = PrintMACaddress(px->dot11Bssid);
					//}
					//std::cout << sMACAddress;

					/*----------------------------------------------------------------------------------*/
					/*----------------------------------------------------------------------------------*/
                    wprintf(L"  BSS Network type[%u]:\t ", j);
                    switch (pBssEntry->dot11BssType) 
						{
						case dot11_BSS_type_infrastructure   :
							wprintf(L"Infrastructure (%u)\n", pBssEntry->dot11BssType);
							break;
						case dot11_BSS_type_independent:
							wprintf(L"Infrastructure (%u)\n", pBssEntry->dot11BssType);
							break;
						default:
							wprintf(L"Other (%lu)\n", pBssEntry->dot11BssType);
							break;
						}
                                
                    wprintf(L"  Number of BSSIDs[%u]:\t %u\n", j, pBssEntry->uNumberOfBssids);	
                    wprintf(L"  Connectable[%u]:\t ", j);
                    if (pBssEntry->bNetworkConnectable)
                        wprintf(L"Yes\n");
                    else 
						{
                        wprintf(L"No\n");
                        wprintf(L"  Not connectable WLAN_REASON_CODE value[%u]:\t %u\n", j, pBssEntry->wlanNotConnectableReason);
						}        
                    wprintf(L"  Number of PHY types supported[%u]:\t %u\n", j, pBssEntry->uNumberOfPhyTypes);

                    if (pBssEntry->wlanSignalQuality == 0)
                        iRSSI = -100;
                    else if (pBssEntry->wlanSignalQuality == 100)   
                        iRSSI = -50;
                    else
                        iRSSI = -100 + (pBssEntry->wlanSignalQuality/2);    
                        
                    wprintf(L"  Signal Quality[%u]:\t %u (RSSI: %i dBm)\n", j, pBssEntry->wlanSignalQuality, iRSSI);
					//Prova con memorizzazione dei MAC
					lMacAddress_TEST.insert(std::make_pair(sMACAddress,iRSSI));
                    if (first_run==true)
					{
						luogo.InsertElement(sMACAddress,iRSSI);
					}
					wprintf(L"  Security Enabled[%u]:\t ", j);
                    if (pBssEntry->bSecurityEnabled)
                        wprintf(L"Yes\n");
                    else
                        wprintf(L"No\n");
         
                    wprintf(L"  Default AuthAlgorithm[%u]: ", j);
                    switch (pBssEntry->dot11DefaultAuthAlgorithm) 
						{
						case DOT11_AUTH_ALGO_80211_OPEN:
							wprintf(L"802.11 Open (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_80211_SHARED_KEY:
							wprintf(L"802.11 Shared (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA:
							wprintf(L"WPA (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA_PSK:
							wprintf(L"WPA-PSK (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_WPA_NONE:
							wprintf(L"WPA-None (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_RSNA:
							wprintf(L"RSNA (%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						case DOT11_AUTH_ALGO_RSNA_PSK:
							wprintf(L"RSNA with PSK(%u)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						default:
							wprintf(L"Other (%lu)\n", pBssEntry->dot11DefaultAuthAlgorithm);
							break;
						}
                        
                    wprintf(L"  Default CipherAlgorithm[%u]: ", j);
                    switch (pBssEntry->dot11DefaultCipherAlgorithm) 
						{
						case DOT11_CIPHER_ALGO_NONE:
							wprintf(L"None (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP40:
							wprintf(L"WEP-40 (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_TKIP:
							wprintf(L"TKIP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_CCMP:
							wprintf(L"CCMP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP104:
							wprintf(L"WEP-104 (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						case DOT11_CIPHER_ALGO_WEP:
							wprintf(L"WEP (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						default:
							wprintf(L"Other (0x%x)\n", pBssEntry->dot11DefaultCipherAlgorithm);
							break;
						}

                    wprintf(L"  Flags[%u]:\t 0x%x", j, pBssEntry->dwFlags);
                    if (pBssEntry->dwFlags) 
						{
                        if (pBssEntry->dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED)
                            wprintf(L" - Currently connected");
                        if (pBssEntry->dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE)
                            wprintf(L" - Has profile");
						}   
                    wprintf(L"\n");
                    
                    wprintf(L"\n");
					if (pWlanBssList!=NULL)
					{
        WlanFreeMemory(pWlanBssList);	//Libera la zona di memoria preposta alla lista di reti disponibili appena utilizzata
        pWlanBssList = NULL;
		}
                }
            }
        }

    }
    if (pBssList != NULL) 
		{
        WlanFreeMemory(pBssList);	//Libera la zona di memoria preposta alla lista di reti disponibili appena utilizzata
        pBssList = NULL;
		}
	

    if (pIfList != NULL) 
		{
        WlanFreeMemory(pIfList);	//Libera la zona di memoria preposta alla lista di NIC appena utilizzata
        pIfList = NULL;
		}
	
		if (first_run==true)
		{
			first_run=false;
		}
		else
		{
			float error;
			error=luogo.ErrorValue(lMacAddress_TEST);
			wprintf(L"Errore con i dati memorizzati: %f\n\n", error);
		}
		WlanCloseHandle(hClient, NULL);
	system("pause");
	}
	return dwRetVal;
}
Example #25
0
int MainWindow::checkWlanHosteed(){
    DWORD dwError = 0;
    DWORD dwServiceVersion = 0;
    HANDLE hClient = NULL;

    if (ERROR_SUCCESS != (dwError = WlanOpenHandle(
                        WLAN_API_VERSION,
                        NULL,               // reserved
                        &dwServiceVersion,
                        &hClient
                        )))
    {
        return dwError;
    }

    // check service version
    if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))
    {
        WlanCloseHandle(hClient, NULL);
        return -1;
    }


    std::string strSSID = "test";
    std::string strSecondaryKey = "123456780";

    // Set the network mode to allow
    BOOL bIsAllow = TRUE;
    WLAN_HOSTED_NETWORK_REASON dwFailedReason;
    DWORD dwReturnValue = WlanHostedNetworkSetProperty(hClient,
                                                       wlan_hosted_network_opcode_enable,
                                                       sizeof(BOOL),
                                                       &bIsAllow,
                                                       &dwFailedReason,
                                                       NULL);

    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    // Set the network SSID and the maximum number of connections
    WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS wlanConnectionSetting;
    memset(&wlanConnectionSetting, 0, sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS));

    // The SSID field in WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS must be of type ANSI, so if the program uses the Unicode, you need to do the conversion.
#ifdef _UNICODE
    WideCharToMultiByte(CP_ACP,
                        0,
                        strSSID.c_str(),   // Save SSID CString types
                        strSSID.length(),    // SSID the length of a string
                        (LPSTR)wlanConnectionSetting.hostedNetworkSSID.ucSSID,
                        32,
                        NULL,
                        NULL);
#else
    memcpy(wlanConnectionSetting.hostedNetworkSSID.ucSSID, strSSID.c_str(), strlen(strSSID.c_str()));
#endif

    wlanConnectionSetting.hostedNetworkSSID.uSSIDLength = strlen((const char*)wlanConnectionSetting.hostedNetworkSSID.ucSSID);
    wlanConnectionSetting.dwMaxNumberOfPeers = 100;

    dwReturnValue = WlanHostedNetworkSetProperty(hClient,
                                                 wlan_hosted_network_opcode_connection_settings,
                                                 sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS),
                                                 &wlanConnectionSetting,
                                                 &dwFailedReason,
                                                 NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    UCHAR keyBuf[100] = {0};
#ifdef _UNICODE
    WideCharToMultiByte(CP_ACP,
                        0,
                        strSecondaryKey.c_str(),
                        strSecondaryKey.length(),
                        (LPSTR)keyBuf,
                        100,
                        NULL,
                        NULL);
#else
    memcpy(keyBuf, strSecondaryKey.c_str(), strSecondaryKey.length());
#endif
    dwReturnValue = WlanHostedNetworkSetSecondaryKey(hClient,
                                                     strlen((const char*)keyBuf) + 1,
                                                     keyBuf,
                                                     TRUE,
                                                     FALSE,
                                                     &dwFailedReason,
                                                     NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        return dwReturnValue;
    }

    dwReturnValue = WlanHostedNetworkStartUsing(hClient, &dwFailedReason, NULL);
    if(ERROR_SUCCESS != dwReturnValue)
    {
        if (wlan_hosted_network_reason_interface_unavailable == dwFailedReason)
        {
            return dwFailedReason;
        }
        return dwReturnValue;
    }



    /*PIP_ADAPTER_INFO pAdapterInfo;
      pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
      ULONG buflen = sizeof(IP_ADAPTER_INFO);

      if(GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) malloc(buflen);
      }

      if(GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) {
        PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
        while (pAdapter) {
          QString str = QString("\tAdapter Name: \t%1\n\
\tAdapter Desc: \t%2\n\
\tIP Address: \t%3\n\
\tGateway: \t%4\n").arg(pAdapter->AdapterName)
                  .arg(pAdapter->Description)
                  //.arg((byte*)pAdapter->Address)
                  .arg(pAdapter->IpAddressList.IpAddress.String)
                  .arg(pAdapter->GatewayList.IpAddress.String);
          pAdapter = pAdapter->Next;
          QMessageBox msg(this);
          msg.setText(str);
          msg.exec();
        }
      } else {
        printf("Call to GetAdaptersInfo failed.\n");
      }*/



    CoInitialize (NULL);

    // init security to enum RAS connections
    CoInitializeSecurity (NULL, -1, NULL, NULL,
                          RPC_C_AUTHN_LEVEL_PKT,
                          RPC_C_IMP_LEVEL_IMPERSONATE,
                          NULL, EOAC_NONE, NULL);

    INetSharingManager * pNSM = NULL;
    HRESULT hr = ::CoCreateInstance (__uuidof(NetSharingManager),
                                     NULL,
                                     CLSCTX_ALL,
                                     __uuidof(INetSharingManager),
                                     (void**)&pNSM);
    if(hr == S_OK){
            // in case it exists already
            //DeletePortMapping (pNSM, NAT_PROTOCOL_TCP, 555);

            // add a port mapping to every shared or firewalled connection.
                    hr = DoTheWork (pNSM);
                   pNSM->Release();
            if (hr!= S_OK){
                return hr;
            }

    }else return hr;

    return 0;
}
HRESULT RunScenario(__in CONFIGURATION_PARAMETERS* configParams)
{
	//common declarations
	UINT status = ERROR_SUCCESS;	
	HRESULT hr = S_OK;
	UINT pinLen = Pin_Length_8;

	//pin needs to be a null terminated ascii char[] for the IWCNDevice::SetPassword function 
	char pin[Pin_Length_8 + 1] = {0};

	
	int result = 0;

	//WCN declarations
	CComPtr<IWCNDevice> pDevice;
	CComObject<WcnConnectNotification>* pWcnConNotif = NULL;	
	CComObject<CWcnFdDiscoveryNotify> * wcnFdDiscoveryNotify = NULL;	

	//Wlan variable declarations
	WCHAR profileBuffer[WCN_API_MAX_BUFFER_SIZE] = {0}; 
	HANDLE wlanHandle = 0;
	DWORD negVersion = 0;
	GUID interfaceGuid = {0};		
	WLAN_INTERFACE_INFO_LIST* pInterfaceList = 0;
	DWORD wlanResult = 0;		
	WLAN_CONNECTION_PARAMETERS connParams;
	ZeroMemory(&connParams,sizeof(connParams));
	WCN_DEVICE_INFO_PARAMETERS WCNDeviceInformation;
	PWSTR pWlanProfileXml = NULL;
	DWORD dwFlags = WLAN_PROFILE_GET_PLAINTEXT_KEY; 


	//The following wlan profile xml is used to configure an unconfigured WCN enabled Router or device.
	//See http://msdn.microsoft.com/en-us/library/bb525370(VS.85).aspx on how to generate a wlan profile.
	//Alternatively, you can read an existing network profile by calling WlanGetProfile.
	WCHAR WCNConnectionProfileTemplate[] =
		L"<?xml version=\"1.0\" ?>"
		L""
		L"<WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">"
		L"    <name>%s</name>"
		L""
		L"    <SSIDConfig>"
		L"        <SSID>"
		L"            <name>%s</name>"
		L"        </SSID>"
		L"    </SSIDConfig>"
		L"    "
		L"    <connectionType>ESS</connectionType>"
		L"    <connectionMode>auto</connectionMode>"
		L""
		L"    <MSM>"
		L"        <security>"
		L"            <authEncryption>"
		L"                <authentication>WPA2PSK</authentication>"
		L"                <encryption>AES</encryption>"
		L"            </authEncryption>"
		L""
		L""
		L"            <sharedKey>"
		L"                <keyType>passPhrase</keyType>"
		L"                <protected>false</protected>"
		L"                <keyMaterial>%s</keyMaterial>"
		L"            </sharedKey>"
		L""
		L"        </security>"
		L"    </MSM>"
		L"</WLANProfile>";


	std::wstring profileXML;

	//open a wlan handle - this will be used later for saving the profile to the system
	status = WlanOpenHandle(
							WLAN_API_VERSION_2_0,
							NULL,
							&negVersion,
							&wlanHandle);

	if (status != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: WlanOpenHandle failed with the following error code [%d]", status);
		hr = S_FALSE;
		goto cleanup;
	}

	// Get the first wlan device
	// ideally you would want to be able to choose the wireless device you want to use
	status = WlanEnumInterfaces(
								wlanHandle,
								NULL,
								&pInterfaceList);

	if(status != ERROR_SUCCESS)
	{				
		wprintf(L"\nERROR: WlanEnumInterfaces failed with the following error code [0x%d]",status);
		hr = S_FALSE;
		goto cleanup;		
	}

	//Make sure there is at least one wlan interface on the system
	if (pInterfaceList == 0 || pInterfaceList->dwNumberOfItems == 0)
	{
		wprintf(L"\nERROR: No wireless network adapters on the system");
		hr = S_FALSE;
		goto cleanup;
	}

	//get the wlan interface GUID
	interfaceGuid = pInterfaceList->InterfaceInfo[0].InterfaceGuid;

	//Create an instance of the IWCNConnectNotify Interface
	hr = CComObject<WcnConnectNotification>::CreateInstance(&pWcnConNotif);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of WcnConnectNotification failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	pWcnConNotif->AddRef();

	hr = CComObject<CWcnFdDiscoveryNotify>::CreateInstance(&wcnFdDiscoveryNotify);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of CWcnFdDiscoveryNotify failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	wcnFdDiscoveryNotify->AddRef();

	//initialize WcnConnectNotification
	hr = pWcnConNotif->Init();
	if(hr !=S_OK)
	{
		wprintf(L"\nERROR: Creating a connection notification event failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}

	//initialize CWcnFdDiscoveryNotify 
	hr = wcnFdDiscoveryNotify->Init(configParams->bTurnOnSoftAP);
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Initializing Function Discovery notify failed with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Search for WCN device with function discovery
	hr = wcnFdDiscoveryNotify->WcnFDSearchStart(&configParams->pDeviceUUID, configParams->pSearchSSID);		
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Function Discovery search failed to start with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Wait for Function Discovery to complete
	wcnFdDiscoveryNotify->WaitForAnyDiscoveryEvent(Discovery_Event_Wait_Time_MS);

	//Attempt to get the IWCNDevice instance
	if(wcnFdDiscoveryNotify->GetWCNDeviceInstance(&pDevice))
	{
		//get information about the device from the IWCNDevice instance
		wprintf(L"\nINFO: The following Device was found by Function Discovery.");
		hr = GetWCNDeviceInformation(pDevice, &WCNDeviceInformation);
		if (hr != S_OK)
		{
			wprintf(L"\nERROR: Failed to get the Device information from the IWCNDevice Instance, hr=[0x%x]", hr);
			goto cleanup;
		}
	}
	else
	{
		wprintf(L"\nERROR: Device was NOT found by Function Discovery.");
		hr = S_FALSE;
		goto cleanup;
	}
	
	

	//The following segment generates a WLAN profile from the template above then saves it to the
	//WLAN store. It the retrieves the profile from the WLAN store for use in configuring a router
	//or device.
	if (configParams->enumConfigScenario != PCConfigPin 
		&& configParams->enumConfigScenario != PCConfigPushButton)
	{
		//add the profiles ssid and passphrase to the wlan profile template
		swprintf_s(
				profileBuffer, 
				WCNConnectionProfileTemplate, 
				configParams->pProfileSSID, 
				configParams->pProfileSSID, 
				configParams->pProfilePassphrase);


		//Add the created profile to the wlan store
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//all-user profile
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile return code was [0x%x]", wlanResult);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the wlan store");
		}

		//Here is where the profile is retrieved from the wlan store to be used in the configuration
		//of the device.  
		//If so desired a list of available profiles could be presented to the user so that 
		//they could decied which profile will be used to configure the device
		//The wlan profile must be retrieved in plain text inorder for the IWCNDEVICE::SetNetWorkProfile
		// method to succeede.  In order to do this you need to be elevated to get the wlan profile
		// in plain text.
		status = WlanGetProfile(
								wlanHandle,
								&interfaceGuid,
								configParams->pProfileSSID,
								NULL,						//reserved
								&pWlanProfileXml,
								&dwFlags,					// Flags - get profile in plain text 
								NULL);						// GrantedAccess - none

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: WlanGetprofile Failed to get profile [%s] with error code [0x%x]", configParams->pProfileSSID, status);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully retrieved profile [%s] from the wlan store.", configParams->pProfileSSID);
		}

		//check to make sure the profile from the wlan store is not a Group Policy profile
		if (WLAN_PROFILE_GROUP_POLICY & dwFlags)
		{
			wprintf(L"\nERROR: Profile [%s] is a group policy WLAN profile which is not supported by WCN", configParams->pProfileSSID);
			hr = S_FALSE;
			goto cleanup;
		}


		//The IWCNDevice::SetNetworkProfile method queues an XML WLAN profile to be 
		//provisioned to the device. This method may only be called prior to IWCNDevice::Connect.
		hr = pDevice->SetNetworkProfile(pWlanProfileXml);
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::SetNetworkProfile failed with error code [0x%x]", hr);
			goto cleanup;
		}
		else
		{				
			wprintf(L"\nINFO: IWCNDevice::SetNetworkProfile() succeeded with result [0x%x]", hr);
		}
	}
	
	switch (configParams->enumConfigScenario)
	{
		case DeviceConfigPushButton:
			
			pinLen = 0;
			break;

		case DeviceConfigPin:
		case RouterConfig:
			if (configParams->pDevicePin == 0)
			{
				wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
				hr = S_FALSE;
				goto cleanup;
			}


			 result = WideCharToMultiByte(
							CP_UTF8,
							0,
							configParams->pDevicePin,
							-1,
							(LPSTR)pin,
							sizeof(pin),
							NULL,
							NULL);
			if (result == 0 )
			{
				wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
				goto cleanup;
			}


			pinLen = sizeof(pin) - 1 ;
			break;

		case PCConfigPushButton:
			//check to make sure the device supports push button before doing the push button configuration
			if (WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_PUSHBUTTON) 
			{
				//set the pin length to 0 this is necessary for a Push button configuration scenario				
				pinLen = 0;
			}
			else
			{
				wprintf(L"ERROR: The [%s] device does not support the Push Button Method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;
			
		case PCConfigPin:
			//check to make sure the device supports pin before doing the pin configuration
			if ((WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_LABEL)|| 
				(WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_DISPLAY))
			{
				if (configParams->pDevicePin == 0)
				{
					wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
					hr = S_FALSE;
					goto cleanup;
				}
			
				result = WideCharToMultiByte(
							CP_UTF8,					//CodePage
							0,							//Unmapped character flags
							configParams->pDevicePin,
							-1,							//null terminated string
							(LPSTR)pin,
							sizeof(pin),
							NULL,						//lpDefaultChar - use system default value
							NULL);						//lpUsedDefaultChar ignored
				if (result == 0 )
				{
					wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
					goto cleanup;
				}

				pinLen = sizeof(pin) - 1 ;

			}
			else
			{
				wprintf(L"\nERROR: The [%s] device does not supprot the pin method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;

		default:
			break;
	}
	
	//The IWCNDevice::SetPassword method configures the authentication method value, and if required, 
	//a password used for the pending session. This method may only be called prior to IWCNDevice::Connect.
	hr = pDevice->SetPassword(
								configParams->enumConfigType, 
								pinLen,
								(BYTE*)pin);

	if(hr != S_OK)
	{	
		wprintf(L"\nERROR: IWCNDevice::SetPassword failed with error code [0x%x]", hr);
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::SetPassword succeeded with result [0x%x]", hr);
	}


	//The IWCNDevice::Connect method initiates the session.
	hr = pDevice->Connect(pWcnConNotif);
	if(hr != S_OK)
	{
		//Device Push button configuration is only supported on SoftAP capable wireless Nics 
		if (hr == HRESULT_FROM_WIN32(ERROR_CONNECTION_UNAVAIL) 
			&& 	configParams->enumConfigScenario == DeviceConfigPushButton)
		{
			wprintf(L"\nERROR: PushButton Configuration of non AP devices is only supported on");
			wprintf(L"\n       SoftAP capable wireless network cards.");
		}
		else
		{
			wprintf(L"\nERROR: IWCNDevice::Connect failed with error code [0x%x]", hr);
		}
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::Connect succeeded with result [0x%x]", hr);
	}

	//wait for the configuration result
	hr = pWcnConNotif->WaitForConnectionResult();
	if (hr != S_OK)
	{
		wprintf(L"ERROR: WaitforconnectionResult returned the following error [ox%x]", hr);
		goto cleanup;
	}

	//check to see which connection callbacks were called
	if(pWcnConNotif->connectSucceededCallBackInvoked)
	{
		wprintf(L"\nINFO: IWCNConnectNotify::ConnectSucceeded was invoked");		
	}
	else if(pWcnConNotif->connectFailedCallBackInvoked)
	{
		wprintf(L"\nERROR: IWCNConnectNotify::ConnectFailed was invoked");
		hr = S_FALSE;
		goto cleanup;
	}

	
	//save the profile from the IWCNDevice instance to the WLAN store if doing a PCConfigPushButton 
	//or a PCConfigPin scenario

	// this is the profile that was received from the router
	if (configParams->enumConfigScenario == PCConfigPushButton  || configParams->enumConfigScenario == PCConfigPin)
	{	
		//The IWCNDevice::GetNetworkProfile method gets a network profile from the device.
		hr = pDevice->GetNetworkProfile(ARRAYSIZE(profileBuffer), profileBuffer);		
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::GetNetworkProfile failed with  [0x%x]", hr);
			goto cleanup;
		}

		//save the profile to the system if doing a RouterConfig or a pushbutton scenario
		//The SoftapConfig and DeviceConfig scenarios will generally use a profile that is already on the system
		//save the profile to the wlan interface			
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//Flags - none
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile to the WLAN store, return code was [0x%x]", wlanResult);
			hr = S_FALSE;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the WLAN store");
		}
	}
	
	//Display the SSID and passphrase used to configure the Router or device
	if (configParams->enumConfigScenario != PCConfigPin && configParams->enumConfigScenario != PCConfigPushButton)
	{
		wprintf(L"\nINFO: Profile SSID Used: [%s]", configParams->pProfileSSID);
		wprintf(L"\nINFO: Profile Passphrase Used: [%s]", configParams->pProfilePassphrase);
	}

cleanup:

	if(pWcnConNotif)
	{
		pWcnConNotif->Release();
		pWcnConNotif = 0;
	}

	if(wcnFdDiscoveryNotify)
	{
		wcnFdDiscoveryNotify->Release();
		wcnFdDiscoveryNotify = 0;
	}

	if (wlanHandle != NULL)
	{
		WlanCloseHandle(wlanHandle,NULL);
	}

	if (pInterfaceList != NULL)
	{
		WlanFreeMemory(pInterfaceList);
	}

	return hr;
}
int get_ap_rssi_data(RADIOMAP &result_map)
{
	HANDLE hClient = NULL;
	DWORD dwMaxClient = 2;
	DWORD dwCurVersion = 0;
	DWORD dwResult = 0;
	DWORD dwRetVal = 0;
	WCHAR GuidString[39] = { 0 };
	PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
	PWLAN_INTERFACE_INFO pIfInfo = NULL;
	PWLAN_BSS_ENTRY pBssEntry = NULL;
	PWLAN_BSS_LIST pBssList = NULL;
	LocalizationNode *pLocalizationNode = NULL;
	std::string mac_id;
	std::string ret_ssid;
	int iRet = 0;
	int ret;
	uint i;

	dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
		return 1;
	}
	dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);
	if (dwResult != ERROR_SUCCESS)
	{
		wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
		return 1;
	}
	else
	{
		wprintf(L"Nunber Entries: %lu\n", pIfList->dwNumberOfItems);
		wprintf(L"Current Index: %lu\n", pIfList->dwIndex);
		for (i = 0; i < (int)pIfList->dwNumberOfItems; i++)
		{
			pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i];
			wprintf(L" Interface Index[%u]:\t %lu\n", i, i);
			iRet = StringFromGUID2(pIfInfo->InterfaceGuid, (LPOLESTR)&GuidString,
				sizeof(GuidString) / sizeof(*GuidString));

			if (iRet == 0)
				wprintf(L"StringFromGUID2 Failed\n");
			else
				wprintf(L"  InterfaceGUID[%d]: %ws\n", i, GuidString);

			wprintf(L"  Interface Description[%d]: %ws", i,
				pIfInfo->strInterfaceDescription);
			wprintf(L"\n");
			wprintf(L"  Interface State[%d]:\t ", i);
			switch (pIfInfo->isState) {
			case wlan_interface_state_not_ready:
				wprintf(L"Not ready\n");
				break;
			case wlan_interface_state_connected:
				wprintf(L"Connected\n");
				break;
			case wlan_interface_state_ad_hoc_network_formed:
				wprintf(L"First node in a ad hoc network\n");
				break;
			case wlan_interface_state_disconnecting:
				wprintf(L"Disconnecting\n");
				break;
			case wlan_interface_state_disconnected:
				wprintf(L"Not connected\n");
				break;
			case wlan_interface_state_associating:
				wprintf(L"Attempting to associate with a network\n");
				break;
			case wlan_interface_state_discovering:
				wprintf(L"Auto configuration is discovering settings for the network\n");
				break;
			case wlan_interface_state_authenticating:
				wprintf(L"In process of authenticating\n");
				break;
			default:
				wprintf(L"Unknown state %ld\n", pIfInfo->isState);
				break;
			}
			wprintf(L"\n");

			const GUID * pGUID = &pIfInfo->InterfaceGuid;
			dwResult = WlanGetNetworkBssList(hClient, pGUID, NULL, dot11_BSS_type_any, 0, NULL, &pBssList);
			if (dwResult != ERROR_SUCCESS)
			{
				wprintf(L"Wlan get network bss list error: %lu\n", dwResult);
				return 1;
			}
			else
			{
				for (uint i = 0; i < pBssList->dwNumberOfItems; i++)
				{
					pBssEntry = &pBssList->wlanBssEntries[i];
					get_mac_id(pBssEntry->dot11Bssid, mac_id);
					if (find_at_radiomap(mac_id, result_map, pLocalizationNode) == 0)
					{
						pLocalizationNode->add_recoder(pBssEntry->lRssi);
					}
					else if (get_ssid(pBssEntry->dot11Ssid, ret_ssid) == 0)
					{
						LocalizationNode new_ap(mac_id, ret_ssid, pBssEntry->lRssi);
						ret = add_to_radiomap(new_ap, result_map);
						if (ret != 0)
						{
							printf("ERROR: add_to_radiomap error");
							exit(1);
						}
					}
				}
			}
		}
	}
	if (pBssList != NULL)
	{
		WlanFreeMemory(pBssList);
		pBssList = NULL;
	}
	if (pIfList != NULL)
	{
		WlanFreeMemory(pIfList);
		pIfList = NULL;
	}
	WlanCloseHandle(hClient, 0);
	return 0;
}
HRESULT 
CWlanManager::Init()
{
    HRESULT hr = S_OK;
    DWORD retCode = ERROR_SUCCESS;
    DWORD dwDataSize = 0;
    BOOL *pbMode = NULL;                                                    // whether hosted network is allowed or not
    PWLAN_HOSTED_NETWORK_CONNECTION_SETTINGS pConnSettings = NULL;          // hosted network connectivity settings
    PWLAN_HOSTED_NETWORK_SECURITY_SETTINGS pSecSettings = NULL;             // hosted network security settings
    PWLAN_HOSTED_NETWORK_STATUS pAPStatus = NULL;                           // hosted network status
    WLAN_OPCODE_VALUE_TYPE valueType;

    Lock();

    if (m_Initialized)
    {
        //
        // no-op because it is already initialized
        //
        BAIL();
    }

    // open a wlan handle first
    retCode = WlanOpenHandle(
                WLAN_API_VERSION,
                NULL,           // reserved
                &m_ServerVersion,
                &m_WlanHandle
                );

    BAIL_ON_WIN32_ERROR(retCode, hr);

    // register notifications
    retCode = WlanRegisterNotification(
                m_WlanHandle,
                WLAN_NOTIFICATION_SOURCE_HNWK,
                TRUE,
                &CWlanManager::WlanNotificationCallback,
                this,
                NULL,       // reserved
                NULL
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // Initialize the hosted network.
    // It is a no-op if the hosted network is already initialized.
    // Bail out if it fails.
    //
    retCode = WlanHostedNetworkInitSettings(
                m_WlanHandle,
                NULL,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // Is hosted network enabled?
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_enable,
                &dwDataSize,
                (PVOID *)&pbMode,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if(!pbMode || dwDataSize < sizeof(BOOL))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }    

    //
    // get the hosted network connectivity settings
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_connection_settings,
                &dwDataSize,
                (PVOID *)&pConnSettings,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if( !pConnSettings || dwDataSize < sizeof(WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }
    
    //
    // get the hosted network seucrity settings
    //
    retCode = WlanHostedNetworkQueryProperty(
                m_WlanHandle,
                wlan_hosted_network_opcode_security_settings,
                &dwDataSize,
                (PVOID *)&pSecSettings,
                &valueType,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    if( !pSecSettings || dwDataSize < sizeof(WLAN_HOSTED_NETWORK_SECURITY_SETTINGS))
    {
        BAIL_ON_WIN32_ERROR(ERROR_INVALID_DATA, hr);
    }

    //
    // get the hosted network status
    //
    retCode = WlanHostedNetworkQueryStatus(
                m_WlanHandle,
                &pAPStatus,
                NULL        // reserved
                );
    BAIL_ON_WIN32_ERROR(retCode, hr);

    //
    // save the values
    //
    m_HostedNetworkAllowed = *pbMode;
    m_HostedNetworkConnSettings = *pConnSettings;
    m_HostedNetworkSecSettings = *pSecSettings;
    m_HostedNetworkState = pAPStatus->HostedNetworkState;

    //
    // add existing stations if the hosted network has started already
    //
    if (wlan_hosted_network_active == pAPStatus->HostedNetworkState)
    {
        for (DWORD i = 0; i < pAPStatus->dwNumberOfPeers; i++)
        {
            OnStationJoin(pAPStatus->PeerList[i]);
        }

    }

    m_Initialized = true;

error:

    if (retCode != ERROR_SUCCESS && m_WlanHandle != NULL)
    {
        //
        // Close WLAN handle in failure cases
        //
        WlanCloseHandle(m_WlanHandle, NULL);
        m_WlanHandle = NULL;
    }

    Unlock();

    if (pbMode != NULL)
    {
        WlanFreeMemory(pbMode);
        pbMode = NULL;
    }

    if (pConnSettings != NULL)
    {
        WlanFreeMemory(pConnSettings);
        pConnSettings = NULL;
    }

    if (pSecSettings != NULL)
    {
        WlanFreeMemory(pSecSettings);
        pSecSettings = NULL;
    }

    if (pAPStatus != NULL)
    {
        WlanFreeMemory(pAPStatus);
        pAPStatus = NULL;
    }

    return hr;
}
Example #29
0
winstd::wlan_handle::~wlan_handle()
{
    if (m_h != invalid)
        WlanCloseHandle(m_h, NULL);
}
Example #30
0
int main(int argc, char *argv[])
{
HANDLE hWlan = NULL;

	DWORD dwError = 0;
	DWORD dwSupportedVersion = 0;
	DWORD dwClientVersion = (IsVistaOrHigher() ? 2 : 1);

	GUID guidInterface; ZeroMemory(&guidInterface, sizeof(GUID));

	WLAN_INTERFACE_INFO_LIST *wlanInterfaceList = (WLAN_INTERFACE_INFO_LIST*)WlanAllocateMemory(sizeof(WLAN_INTERFACE_INFO_LIST));
	ZeroMemory(wlanInterfaceList, sizeof(WLAN_INTERFACE_INFO_LIST));

	WLAN_AVAILABLE_NETWORK_LIST *wlanNetworkList = (WLAN_AVAILABLE_NETWORK_LIST*)WlanAllocateMemory(sizeof(WLAN_AVAILABLE_NETWORK_LIST));
	ZeroMemory(wlanNetworkList, sizeof(WLAN_AVAILABLE_NETWORK_LIST));

	try
	{
		if(dwError = WlanOpenHandle(dwClientVersion, NULL, &dwSupportedVersion, &hWlan) != ERROR_SUCCESS)
			throw("[x] Unable access wireless interface");

		if(dwError = WlanEnumInterfaces(hWlan, NULL, &wlanInterfaceList) != ERROR_SUCCESS)
			throw("[x] Unable to enum wireless interfaces");

		wprintf(L"[!] Found adapter %s\n", wlanInterfaceList->InterfaceInfo[0].strInterfaceDescription);

		if(dwError = wlanInterfaceList->InterfaceInfo[0].isState != wlan_interface_state_not_ready)
		{
				if(wlanInterfaceList->dwNumberOfItems > 1)
				{
					// TODO: Add processing for multiple wireless cards here
					printf("[!] Detected multiple wireless adapters, using default\n");
					guidInterface = wlanInterfaceList->InterfaceInfo[0].InterfaceGuid;
				}
				else
				{
					guidInterface = wlanInterfaceList->InterfaceInfo[0].InterfaceGuid;
				}
		}
		else
			throw("[x] Default wireless adapter disabled");

		DWORD dwPrevNotif = 0;

		// Scan takes awhile so we need to register a callback
		if(dwError = WlanRegisterNotification(hWlan, WLAN_NOTIFICATION_SOURCE_ACM, TRUE,
		  (WLAN_NOTIFICATION_CALLBACK)WlanNotification, NULL, NULL, &dwPrevNotif) != ERROR_SUCCESS)
			throw("[x] Unable to register for notifications");

		printf("[i] Scanning for nearby networks...\n");
		if(dwError = WlanScan(hWlan, &guidInterface, NULL, NULL, NULL) != ERROR_SUCCESS)
			throw("[x] Scan failed, check adapter is enabled");

		// Yawn...
		while(bWait)
			Sleep(100);

		// Unregister callback, don't care if it succeeds or not
		WlanRegisterNotification(hWlan, WLAN_NOTIFICATION_SOURCE_NONE, TRUE, NULL, NULL, NULL, &dwPrevNotif);

		if(dwError = WlanGetAvailableNetworkList(hWlan, &guidInterface, NULL, NULL, &wlanNetworkList) != ERROR_SUCCESS)
			throw("[x] Unable to obtain network list");

		for(unsigned int i = 0; i < wlanNetworkList->dwNumberOfItems; i++)
		{
				printf("\nSSID:\t\t\t%s\nSIGNAL:\t\t\t%d%%\n",
						wlanNetworkList->Network[i].dot11Ssid.ucSSID,
						wlanNetworkList->Network[i].wlanSignalQuality);

				printf("SECURITY:\t\t");
				switch(wlanNetworkList->Network[i].dot11DefaultAuthAlgorithm)
				{
						case DOT11_AUTH_ALGO_80211_OPEN:
						case DOT11_AUTH_ALGO_80211_SHARED_KEY:
							printf("WEP");
						break;

						case DOT11_AUTH_ALGO_WPA:
						case DOT11_AUTH_ALGO_WPA_PSK:
						case DOT11_AUTH_ALGO_WPA_NONE:
							printf("WPA");
						break;

						case DOT11_AUTH_ALGO_RSNA:
						case DOT11_AUTH_ALGO_RSNA_PSK:
							printf("WPA2");
						break;

						default:
							printf("UNKNOWN");
						break;
				}
				printf("\n");
		}
	}
	catch(char *szError)
	{
		printf("%s (0x%X)\nQuitting...\n", szError);
	}

	if(wlanNetworkList)
		WlanFreeMemory(wlanNetworkList);
	if(wlanInterfaceList)
		WlanFreeMemory(wlanInterfaceList);
	if(hWlan)
		WlanCloseHandle(hWlan, NULL);

	return dwError;
}