C#使用managedwif连接wifi(支持WPA2_PSK、WPA2_PSK、WEP)

http://pan.baidu.com/s/1c0Iqsve       managedwif及代码

public partial class Form1 : Form
    {
        //连接状态
        public enum e_login_status
        {
            success,
            fail,
            interrupt,
        }

        //判读是否连接
        bool m_Loginresult = false;

        //Wifi信息列表
        public List ssids = new List();

        //获取Wifi信号列表
        private void GetWirless()
        {
            try
            {
                List> list_ssid = new List>();
                WlanClient client = new WlanClient();
                foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
                {
                    Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles);
                    foreach (Wlan.WlanAvailableNetwork network in networks)
                    {
                        
                        if (GetStringForSSID(network.dot11Ssid) == "0" || GetStringForSSID(network.dot11Ssid).Trim() == "")
                           continue;
                        if (network.flags != 0)//用于过滤掉系统无线管理中已记住的网络,否则有重复项
                           continue;
string value = "SSID【" + GetStringForSSID(network.dot11Ssid) + "】 信号强度【" + network.wlanSignalQuality + "】"; string key = GetStringForSSID(network.dot11Ssid); KeyValuePair kv = new KeyValuePair(key, value); list_ssid.Add(kv); } //t_cmb_SSID.ValueMember = "key"; //t_cmb_SSID.DisplayMember = "value"; //t_cmb_SSID.DataSource = list_ssid; } } catch (Exception ex) { MessageBox.Show(ex.Message); Log4NetComon.AppLog.Write(this.ToString(), Log4NetComon.AppLog.LogMessageType.Info, ex); } } private string GetStringForSSID(Wlan.Dot11Ssid ssid) { return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength); } /// /// 连接选定的WIFI /// /// ssid名称 /// 密码 private void Connection(string ssid, string key) { foreach (var item in ssids) { if (item.SSID == ssid) { for (int i = 0; i < 3; i++)//信号有时不好,未必一次就可以连接成功,连接上马上跳出循环 { e_login_status state = ConnectToSSID(item, key); if (state == e_login_status.success) { m_Loginresult = true; //item.wlanInterface.Disconnect();//断开连接 return; } else if (state == e_login_status.interrupt) break; } } } } private void t_btn_connection_Click(object sender, EventArgs e) { string ssid = "TP_Link_2D0000"; string key = ""; if (ssid == "0" || ssid == "") return; ScanSSID(); Connection(ssid, key); if (m_Loginresult) MessageBox.Show("连接成功"); else MessageBox.Show("连接失败"); m_Loginresult = false; } /// /// 枚举所有无线设备接收到的SSID /// public void ScanSSID() { ssids = new List(); WlanClient client = new WlanClient(); foreach (WlanClient.WlanInterface wlanIface in client.Interfaces) { // Lists all networks with WEP security //Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0); Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles); foreach (Wlan.WlanAvailableNetwork network in networks) {
                    if (GetStringForSSID(network.dot11Ssid) == "0" || GetStringForSSID(network.dot11Ssid).Trim() == "")
                        continue;
                    if (network.flags != 0)//用于过滤掉系统无线管理中已记住的网络,否则有重复项
                        continue;
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; targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm; ssids.Add(targetSSID); } } } /// /// 字符串转Hex /// /// /// public static string StringToHex(string str) { StringBuilder sb = new StringBuilder(); byte[] byStr = System.Text.Encoding.UTF8.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()); } /// /// 连接到未加密的SSID /// /// public e_login_status ConnectToSSID(WIFISSID ssid, string key) { try { String auth = ""; String cipher = ""; bool isNoKey = false; String keytype = ""; switch (ssid.dot11DefaultAuthAlgorithm) { case Wlan.Dot11AuthAlgorithm.IEEE80211_Open: auth = "open"; break; //case Wlan.Dot11AuthAlgorithm.IEEE80211_SharedKey: // 'not implemented yet; //break; case Wlan.Dot11AuthAlgorithm.RSNA: auth = "WPA2PSK"; break; case Wlan.Dot11AuthAlgorithm.RSNA_PSK: auth = "WPA2PSK"; break; case Wlan.Dot11AuthAlgorithm.WPA: auth = "WPAPSK"; break; case Wlan.Dot11AuthAlgorithm.WPA_None: auth = "WPAPSK"; break; case Wlan.Dot11AuthAlgorithm.WPA_PSK: auth = "WPAPSK"; break; } switch (ssid.dot11DefaultCipherAlgorithm) { case Wlan.Dot11CipherAlgorithm.CCMP: cipher = "AES"; keytype = "passPhrase"; break; case Wlan.Dot11CipherAlgorithm.TKIP: cipher = "TKIP"; keytype = "passPhrase"; break; case Wlan.Dot11CipherAlgorithm.None: cipher = "none"; keytype = ""; isNoKey = true; break; case Wlan.Dot11CipherAlgorithm.WEP: cipher = "WEP"; keytype = "networkKey"; break; case Wlan.Dot11CipherAlgorithm.WEP40: cipher = "WEP"; keytype = "networkKey"; break; case Wlan.Dot11CipherAlgorithm.WEP104: cipher = "WEP"; keytype = "networkKey"; break; } if (isNoKey && key != "") return e_login_status.interrupt; else if (!isNoKey && key == "") return e_login_status.interrupt; else { string profileName = ssid.SSID; // this is also the SSID string mac = StringToHex(profileName); // string profileXml = ""; if (key != "") profileXml = string.Format("{0}{1}{0}ESSautofalse{2}{3}false{4}false{5}0", profileName, mac, auth, cipher, keytype, key); else profileXml = string.Format("{0}{1}{0}ESSautofalse{2}{3}false", profileName, mac, auth, cipher, keytype); ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true); bool b = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000); if (b) return e_login_status.success; else return e_login_status.fail; } } catch (Exception ex) { MessageBox.Show(ex.Message); return e_login_status.interrupt; } } } public class WIFISSID2 { public string SSID = "NONE"; public Wlan.Dot11AuthAlgorithm dot11DefaultAuthAlgorithm = Wlan.Dot11AuthAlgorithm.IEEE80211_Open; public Wlan.Dot11CipherAlgorithm dot11DefaultCipherAlgorithm = Wlan.Dot11CipherAlgorithm.CCMP; public bool networkConnectable = true; public string wlanNotConnectableReason = ""; public int wlanSignalQuality = 0; public WlanClient.WlanInterface wlanInterface = null; }
 
  


你可能感兴趣的:(C#)