C#編程使用Managed Wifi API連接無線SSID


http://i.isclab.org/?p=299

在windows平台下,可以使用native wifi api來控制無線網卡,包括獲取無線網卡參數,獲取周圍無線接入點參數等功能,在windows xp sp2版本的系統上,使用需要下載一個KB918997補丁包才能支持,下載地址如下:http://support.microsoft.com/kb/918997/en-us。而在xp sp3、vista、win7等高版本操作系統中,已經包含了此庫,所以可以直接使用。

使用的api最好的文檔當然是MSDN,地址如下:http://msdn.microsoft.com/en-us/library/ms706275(v=VS.85).aspx。里面詳細介紹所用到的枚舉類型、結構體、函數等,並且提供了非常好的實例代碼。

 

如何用C#去操作無線網卡連接無線網絡一直是個人學習過程中的一大困惑。好在最近成功解決了這個問題。最近在寫一個中國電信ChinaNet無線熱點自動連接工具,期間用到了Managed Wifi API,使用起來很是方便。

操作步驟很簡單:

1.下載Managed Wifi API

關於Managed Wifi API:This project is a .NET class library allowing you to control Wifi (802.11) network adapters installed in your Windows machine programmatically.

The library uses the Native Wifi API, available since Windows Vista and Windows XP SP2 (in a limited fashion, and only after applying a hotfix provided in KB article 918997). Older versions of Windows are not supported.

2.創建C#工程文件,並添加對ManagedWifi.dll的引用。

3.編寫代碼,引用“Native Wifi API”。 關鍵代碼如下:

 

using System;
using System.Collections.Generic;
using System.Text;
using NativeWifi;
 
 
namespace ManagedWifiExample
{
    class MyWifi
    {
        public List<WIFISSID> ssids = new List<WIFISSID>();
 
        public MyWifi()
        {
            ssids.Clear();
        }
 
 
        static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }
 
        /// <summary>
        /// 枚舉所有無線設備接收到的SSID
        /// </summary>
        public void ScanSSID()
        {
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                // Lists all networks with WEP security
                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                foreach (Wlan.WlanAvailableNetwork network in networks)
                {
                    WIFISSID targetSSID = new WIFISSID();
 
                    targetSSID.wlanInterface = wlanIface;
                    targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality;
                    targetSSID.SSID = GetStringForSSID(network.dot11Ssid);
                    //targetSSID.SSID = Encoding.Default.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);
                    targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm.ToString();
                    targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString();
                    ssids.Add(targetSSID);
 
                    //if ( network.dot11DefaultCipherAlgorithm == Wlan.Dot11CipherAlgorithm.WEP )
                    //{
                    //    Console.WriteLine( "Found WEP network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
                    //}
                    //Console.WriteLine("Found network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
                    //Console.WriteLine("dot11BssType:{0}.", network.dot11BssType.ToString());
                    //Console.WriteLine("dot11DefaultAuthAlgorithm:{0}.", network.dot11DefaultAuthAlgorithm.ToString());
                    //Console.WriteLine("dot11DefaultCipherAlgorithm:{0}.", network.dot11DefaultCipherAlgorithm.ToString());
                    //Console.WriteLine("dot11Ssid:{0}.", network.dot11Ssid.ToString());
 
                    //Console.WriteLine("flags:{0}.", network.flags.ToString());
                    //Console.WriteLine("morePhyTypes:{0}.", network.morePhyTypes.ToString());
                    //Console.WriteLine("networkConnectable:{0}.", network.networkConnectable.ToString());
                    //Console.WriteLine("numberOfBssids:{0}.", network.numberOfBssids.ToString());
                    //Console.WriteLine("profileName:{0}.", network.profileName.ToString());
                    //Console.WriteLine("wlanNotConnectableReason:{0}.", network.wlanNotConnectableReason.ToString());
                    //Console.WriteLine("wlanSignalQuality:{0}.", network.wlanSignalQuality.ToString());
                    //Console.WriteLine("-----------------------------------");
                    // Console.WriteLine(network.ToString());
                }
            }
        } // EnumSSID
 
 
        /// <summary>
        /// 連接到未加密的SSID
        /// </summary>
        /// <param name="ssid"></param>
        public void ConnectToSSID(WIFISSID ssid)
        {
            // Connects to a known network with WEP security
            string profileName = ssid.SSID; // this is also the SSID
 
            string mac = StringToHex(profileName); // 
 
            //string key = "";
            //string profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>New{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><MSM><security><authEncryption><authentication>open</authentication><encryption>none</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>networkKey</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>", profileName, mac, key);
            //string profileXml2 = "<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>Hacker SSID</name><SSIDConfig><SSID><hex>54502D4C494E4B5F506F636B657441505F433844323632</hex><name>TP-LINK_PocketAP_C8D262</name></SSID>        </SSIDConfig>        <connectionType>ESS</connectionType><connectionMode>manual</connectionMode><MSM> <security><authEncryption><authentication>open</authentication><encryption>none</encryption><useOneX>false</useOneX></authEncryption></security></MSM></WLANProfile>";
            //wlanIface.SetProfile( Wlan.WlanProfileFlags.AllUser, profileXml2, true );
            //wlanIface.Connect( Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName );
            string myProfileXML = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>manual</connectionMode><MSM><security><authEncryption><authentication>open</authentication><encryption>none</encryption><useOneX>false</useOneX></authEncryption></security></MSM></WLANProfile>", profileName, mac);
            ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, myProfileXML, true);
            ssid.wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
            //Console.ReadKey();
        }
 
        /// <summary>
        /// 字符串轉Hex
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringToHex(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.Default.GetBytes(str); //默認是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(Convert.ToString(byStr[i], 16));
            }
 
            return (sb.ToString().ToUpper());
        }
    }
 
    class WIFISSID
    {
        public string SSID = "NONE";
        public string dot11DefaultAuthAlgorithm = "";
        public string dot11DefaultCipherAlgorithm = "";
        public bool networkConnectable = true;
        public string wlanNotConnectableReason = "";
        public int wlanSignalQuality = 0;
        public WlanClient.WlanInterface wlanInterface = null;
    }
 
}

4.示例程序允許枚舉當前網卡接收到的所有無線SSID,並支持接入開放認證(無密碼)的無線熱點。

5.其它

Wifi XML配置文件請參考微軟文檔

http://www.microsoft.com/networking/WLAN/profile/v1

C#編程使用Managed Wifi API連接無線SSID示例代碼下載

 ===============================================

轉載后個人遇到的問題:

設置WIFI密碼后,不能設置和打開WIFI連接問題解決方案:

需要修改profileXml中的配置信息,要和WIFI設置的一樣,不然不能設置和訪問WIFI的哦!【個人測試經驗】

 本人的設置

 string profileXml = string.Format("<?xml version=\"1.0\" encoding=\"US-ASCII\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>WPAPSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{1}</keyMaterial></sharedKey></security></MSM></WLANProfile>", profileName, key);

 

==================================================

 

 

轉載:http://i.isclab.org/?p=299


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM