1. 程式人生 > >C#程式設計使用Managed Wifi API連線wifi整理(一)

C#程式設計使用Managed Wifi API連線wifi整理(一)

一、Managed Wifi API簡介

1.這是一個.Net類庫允許控制無線網路介面卡(802.11)安裝在你的Windows機器程式設計。

4.這個類庫的wlanapi不是特別全....

二、更多相關資料

三、簡單使用例項

1.引用 ManagedWifi.dll,using NativeWifi; 

2.C#程式碼

   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;  
    }  
    
}  

3.帶密碼的Xml檔案
<?xml version="1.0" encoding="utf-8" ?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
  <name>nicaimimashisha</name>
  <SSIDConfig>
    <SSID>
      <hex>6E696361696D696D61736869736861</hex>
      <name>nicaimimashisha</name>
    </SSID>
  </SSIDConfig>
  <connectionType>ESS</connectionType>
  <connectionMode>auto</connectionMode>
  <MSM>
    <security>
      <authEncryption>
        <authentication>WPA2PSK</authentication>
        <encryption>AES</encryption>
        <useOneX>false</useOneX>
      </authEncryption>
      <sharedKey>
        <keyType>passPhrase</keyType>
        <protected>true</protected>
        <keyMaterial>01000000D08C9DDF0115D1118C7A00C04FC297EB010000004F479E51D4435D409C4B5FC05DF1BD2D000000000200000000001066000000010000200000005C53C70A83EBEA47512B9F87B34EC7C405E9B4ACDBFFFEBEA8B5DA6D6958E6A8000000000E8000000002000020000000F95172637168CC535A909A1CC8021C003077AD958B38C2C01F5B1CF6AB3F87B4100000005D3361250B2140E1B14D0F66D36F2CA640000000C49084078E63F00188D3CF0B80EE9127EEDFAEABAB01803D5E0480A89811E3B24FEF3EA45FF713BB9C244EABC1C2C119CAC4FE192ACF60C976027112262A4E3F</keyMaterial>
      </sharedKey>
    </security>
  </MSM>
  <MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
    <enableRandomization>false</enableRandomization>
  </MacRandomization>
</WLANProfile>
特別說明:keyMaterial必須是根據指定加密方法加密之後的資料

4.事件監聽:

 wlanIface.WlanConnectionNotification += WlanIface_WlanConnectionNotification;
private static void WlanIface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData,
    Wlan.WlanConnectionNotificationData connNotifyData)
{
    Console.WriteLine(".....................");
    Console.WriteLine(notifyData.NotificationCode);
    Console.WriteLine(notifyData.notificationSource);
}


4.獲取已經連線過的Xml配置檔案
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)
{
    //Console.WriteLine(network.profileName);
    //Console.WriteLine(GetStringForSSID(network.dot11Ssid));
    //Console.WriteLine(network.dot11DefaultCipherAlgorithm);
    //Console.WriteLine("*********************************");

    //if (network.dot11DefaultCipherAlgorithm == Wlan.Dot11CipherAlgorithm.WEP)
    //{
    //    Console.WriteLine("Found WEP network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
    //}
}

// Retrieves XML configurations of existing profiles.
// This can assist you in constructing your own XML configuration
// (that is, it will give you an example to follow).
foreach (Wlan.WlanProfileInfo profileInfo in wlanIface.GetProfiles())
{
    string name = profileInfo.profileName; // this is typically the network's SSID
    string xml = wlanIface.GetProfileXml(profileInfo.profileName);
    Console.WriteLine("ssid:" + name);
    Console.WriteLine(xml);
    Console.WriteLine("******************************************************");
}

}
獲取結果:
******************************************************
ssid:123
<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
        <name>123</name>
        <SSIDConfig>
                <SSID>
                        <hex>313233</hex>
                        <name>123</name>
                </SSID>
        </SSIDConfig>
        <connectionType>ESS</connectionType>
        <connectionMode>auto</connectionMode>
        <MSM>
                <security>
                        <authEncryption>
                                <authentication>WPA2PSK</authentication>
                                <encryption>AES</encryption>
                                <useOneX>false</useOneX>
                        </authEncryption>
                        <sharedKey>
                                <keyType>passPhrase</keyType>
                                <protected>true</protected>
                                <keyMaterial>01000000D08C9DDF0115D1118C7A00C04FC297EB010000004F479E51D4435D409C4B5FC05DF1BD2D00000000020000000000106600000001000020000000EF6E93D46740330472CADC868CA81CF587AFD3D6D8C3B734066CFC27A25025F7000000000E80000000020000200000002A290E5F01D301902EB7ECD21E37336CCB32825DFB2FC8A1A71D2F3B4E173AF81000000071CC3F3EBF21D55DF27136D77246EB9C400000008A8607C942F8DF619AE1FDD56E556DDC3D86F567FCF043EFD9D7CFD7263B31F4D27D6FECE6BC18843EE479430FE0563E19E08A6186D7B45DBB5FF034D70D43EC</keyMaterial>
                        </sharedKey>
                </security>
        </MSM>
        <MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
                <enableRandomization>false</enableRandomization>
        </MacRandomization>
</WLANProfile>

******************************************************
ssid:nicaimimashisha
<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
        <name>nicaimimashisha</name>
        <SSIDConfig>
                <SSID>
                        <hex>6E696361696D696D61736869736861</hex>
                        <name>nicaimimashisha</name>
                </SSID>
        </SSIDConfig>
        <connectionType>ESS</connectionType>
        <connectionMode>auto</connectionMode>
        <MSM>
                <security>
                        <authEncryption>
                                <authentication>WPA2PSK</authentication>
                                <encryption>AES</encryption>
                                <useOneX>false</useOneX>
                        </authEncryption>
                        <sharedKey>
                                <keyType>passPhrase</keyType>
                                <protected>true</protected>
                                <keyMaterial>01000000D08C9DDF0115D1118C7A00C04FC297EB010000004F479E51D4435D409C4B5FC05DF1BD2D000000000200000000001066000000010000200000005C53C70A83EBEA47512B9F87B34EC7C405E9B4ACDBFFFEBEA8B5DA6D6958E6A8000000000E8000000002000020000000F95172637168CC535A909A1CC8021C003077AD958B38C2C01F5B1CF6AB3F87B4100000005D3361250B2140E1B14D0F66D36F2CA640000000C49084078E63F00188D3CF0B80EE9127EEDFAEABAB01803D5E0480A89811E3B24FEF3EA45FF713BB9C244EABC1C2C119CAC4FE192ACF60C976027112262A4E3F</keyMaterial>
                        </sharedKey>
                </security>
        </MSM>
        <MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
                <enableRandomization>false</enableRandomization>
        </MacRandomization>
</WLANProfile>

******************************************************
更多參考:

http://blog.csdn.net/m593192219/article/details/9363355