C#WIFI搜索与连接

1、功能搜索WIFI并连接

2、所用工具及资源:VS2012 Managed Wifi API(即:引用ManagedWifi.dll文件地址:http://files.cnblogs.com/files/ywf520/ManagedWifi.zip)

3、运行截图及工程截图:

工程目录 结构

4、具体代码实现

wifiSo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NativeWifi; 

namespace WifiConnect
{
    class wifiSo
    {
        private WIFISSID ssid;               //wifi ssid
        private string key;                 //wifi密码
        public List<WIFISSID> ssids = new List<WIFISSID>();

        public wifiSo()
        {
            ssids.Clear();
        }

        public wifiSo(WIFISSID ssid, string key)
        {
            ssids.Clear();
            this.ssid = ssid;
            this.key = key;
        }

        //寻找当前连接的网络:
        public static string GetCurrentConnection()
        {
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                foreach (Wlan.WlanAvailableNetwork network in networks)
                {
                    if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)
                    {
                        return wlanIface.CurrentConnection.profileName;
                    }
                }
            }

            return string.Empty;
        }
        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);
                }
            }
        } 

        // 字符串转Hex
        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());

        }

        // 连接到无线网络
        public void ConnectToSSID()
        {
            try
            {
                String auth = string.Empty;
                String cipher = string.Empty;
                bool isNoKey = false;
                String keytype = string.Empty;
                //Console.WriteLine("》》》《《" + ssid.dot11DefaultAuthAlgorithm + "》》对比《《" + "Wlan.Dot11AuthAlgorithm.RSNA_PSK》》");
                switch (ssid.dot11DefaultAuthAlgorithm)
                {
                    case "IEEE80211_Open":
                        auth = "open"; break;
                    case "RSNA":
                        auth = "WPA2PSK"; break;
                    case "RSNA_PSK":
                        //Console.WriteLine("电子设计wifi:》》》");
                        auth = "WPA2PSK"; break;
                    case "WPA":
                        auth = "WPAPSK"; break;
                    case "WPA_None":
                        auth = "WPAPSK"; break;
                    case "WPA_PSK":
                        auth = "WPAPSK"; break;
                }
                switch (ssid.dot11DefaultCipherAlgorithm)
                {
                    case "CCMP":
                        cipher = "AES";
                        keytype = "passPhrase";
                        break;
                    case "TKIP":
                        cipher = "TKIP";
                        keytype = "passPhrase";
                        break;
                    case "None":
                        cipher = "none"; keytype = "";
                        isNoKey = true;
                        break;
                    case "WWEP":
                        cipher = "WEP";
                        keytype = "networkKey";
                        break;
                    case "WEP40":
                        cipher = "WEP";
                        keytype = "networkKey";
                        break;
                    case "WEP104":
                        cipher = "WEP";
                        keytype = "networkKey";
                        break;
                }

                if (isNoKey && !string.IsNullOrEmpty(key))
                {

                    Console.WriteLine(">>>>>>>>>>>>>>>>>无法连接网络!");
                    return;
                }
                else if (!isNoKey && string.IsNullOrEmpty(key))
                {
                    Console.WriteLine("无法连接网络!");
                    return;
                }
                else
                {
                    //string profileName = ssid.profileNames; // this is also the SSID
                    string profileName = ssid.SSID;
                    string mac = StringToHex(profileName);
                    string profileXml = string.Empty;
                    if (!string.IsNullOrEmpty(key))
                    {
                        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>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>{2}</authentication><encryption>{3}</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>{4}</keyType><protected>false</protected><keyMaterial>{5}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>",
                            profileName, mac, auth, cipher, keytype, key);
                    }
                    else
                    {
                        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>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>{2}</authentication><encryption>{3}</encryption><useOneX>false</useOneX></authEncryption></security></MSM></WLANProfile>",
                            profileName, mac, auth, cipher, keytype);
                    }

                    ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);

                    bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);
                    if (!success)
                    {
                        Console.WriteLine("连接网络失败!");
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("连接网络失败!");
                return;
            }
        }
        //当连接的连接状态进行通知 面是简单的通知事件的实现,根据通知的内容在界面上显示提示信息:
        private void WlanInterface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
        {
            try
            {
                    if (notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
                    {
                        int notificationCode = (int)notifyData.NotificationCode;
                        switch (notificationCode)
                        {
                            case (int)Wlan.WlanNotificationCodeAcm.ConnectionStart:

                                Console.WriteLine("开始连接无线网络.......");
                                break;
                            case (int)Wlan.WlanNotificationCodeAcm.ConnectionComplete:

                                break;
                            case (int)Wlan.WlanNotificationCodeAcm.Disconnecting:

                                Console.WriteLine("正在断开无线网络连接.......");
                                break;
                            case (int)Wlan.WlanNotificationCodeAcm.Disconnected:
                                Console.WriteLine("已经断开无线网络连接.......");
                                break;
                        }
                    }
                //}));
            }
            catch (Exception e)
            {
                //Loger.WriteLog(e.Message);
            }
        }
    }

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

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NativeWifi;
using System.Threading;
namespace WifiConnect
{
    public partial class wifi : Form
    {
        private List<WIFISSID> ssids;
        private wifiSo wifiso;
        public wifi()
        {
            InitializeComponent();
        }

        private void wifi_Load(object sender, EventArgs e)
        {

            wifiso = new wifiSo();  //加载wifi
            ssids = wifiso.ssids;
            wifiso.ScanSSID();      //显示所有wifi

        }
        private void connectWIFI()
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.wifiListOK.Items.Clear();  //只移除所有的项。
            //wifiListOK.Clear();//清除listview中的数据
            SetwifiList();
            ScanSSID();
        }

        //设置listviewok
        private void SetwifiList()
        {
            this.wifiListOK.Columns.Add("wifi名称", 160, HorizontalAlignment.Left); //一步添加
            this.wifiListOK.Columns.Add("wifiSSID", 120, HorizontalAlignment.Left); //一步添加
            this.wifiListOK.Columns.Add("加密方式", 100, HorizontalAlignment.Left); //一步添加
            this.wifiListOK.Columns.Add("信号强度", 88, HorizontalAlignment.Left); //一步添加
            //ColumnHeader ch = new ColumnHeader();  //先创建列表头
            wifiListOK.GridLines = true;//显示网格
            wifiListOK.Scrollable = true;//显示所有项时是否显示滚动条
            wifiListOK.AllowColumnReorder = true;
            wifiListOK.FullRowSelect = true;
            wifiListOK.CheckBoxes = true;
        }
        //添加数据
        private void wifiListOKADDitem(String wifiname, String pass,String dot11DefaultAuthAlgorithm,int i)
        {
            this.wifiListOK.BeginUpdate();   //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度
            //this.wifiListOK.Items.Add(wifiname,0);
            ListViewItem wifiitem = wifiListOK.Items.Add(wifiname);

            wifiitem.SubItems.Add(pass);
            wifiitem.SubItems.Add(dot11DefaultAuthAlgorithm);
            wifiitem.SubItems.Add(i+"");

            this.wifiListOK.EndUpdate();  //结束数据处理,UI界面一次性绘制。
            this.wifiListOK.View = System.Windows.Forms.View.Details;
        }

        //单击事件
        private void wifiListOK_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (wifiListOK.SelectedIndices != null && wifiListOK.SelectedItems.Count > 0)
            {
                ListView.SelectedIndexCollection c = wifiListOK.SelectedIndices;
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("确定要连接" + wifiListOK.Items[c[0]].Text + "吗?", "wifi连接", messButton);
                 if (dr == DialogResult.OK)//如果点击“确定”按钮
                 {
                    // Console.WriteLine("<<<<<<<<<<<<<<<<flags:{0}.>>>>>>>>>>>>>>>>>>>>>>>", ssid);
                     //wifiso.ConnectToSSID(targetSSID, "ZMZGZS520");//连接wifi
                 }
            }
        }
        static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }
        //显示所有wifi
        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);
                    wifiListOKADDitem(GetStringForSSID(network.dot11Ssid), network.dot11DefaultCipherAlgorithm.ToString(),
                        network.dot11DefaultAuthAlgorithm.ToString(),(int)network.wlanSignalQuality);
                    if (GetStringForSSID(network.dot11Ssid).Equals("DZSJ1"))
                    {
                        var obj = new wifiSo(targetSSID, "ZMZGZS520");
                        Thread wificonnect = new Thread(obj.ConnectToSSID);
                        wificonnect.Start();
                        //wifiso.ConnectToSSID(targetSSID, "ZMZGZS520");//连接wifi
                        connectWifiOK.Text = GetStringForSSID(network.dot11Ssid);
                        Image img = new Bitmap(Environment.CurrentDirectory+"/image/wifi.png");//这里是你要替换的图片。当然你必须事先初始化出来图
                        pictureBoxW.BackgroundImage = img;
                        //Console.WriteLine(">>>>>>>>>>>>>>>>>开始连接网络!" + targetSSID.SSID + GetStringForSSID(network.dot11Ssid) + GetStringForSSID(network.dot11Ssid).Equals("DZSJ1"));
                    }

                }
            }
        }
        /// <summary>
        /// 关闭wifi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeWIFI_Click(object sender, EventArgs e)
        {
            if (connectWifiOK.Text.Equals("无") || connectWifiOK.Text.Equals(null))
            {
                MessageBox.Show("当前无连接wifi");
            }
            else
            {

            }
        }
        //更新数据
        private void getwifidatabtn_Click(object sender, EventArgs e)
        {
            WifiSocket wifiscoket = new WifiSocket();
            wifiscoket.fuwu();
            wifiscoket.kehuduan();
        }
    }
}

5、到此就结束了,写的不对的地方希望大家多多指教,更多功能还希望小伙伴们继续研究。

6、鸣谢:感谢各位广大博友无私的分享精神!

7、参考:http://blog.csdn.net/m593192219/article/details/9363355

时间: 2024-10-16 20:30:21

C#WIFI搜索与连接的相关文章

Python wifi掉线重连接

原理很简单,通过python执行dos命令 : ping 和 netsh 需要用到os和time模块 代码如下: >>> import os >>> print 'wifi掉线' wifi掉线 >>> import time >>> while True: ... status = os.system("ping -c 1 www.baidu.com") ... if status == 1: ... print

树莓派wifi无路由器连接

应该有相当一部分同学在如何用wifi进行树莓派连接遇到一些瓶颈,网上说的一般都需要一个路由器,其实不然,我们下载一个360免费wifi即可,相当于电脑当作路由器来分享网络,祥细步骤如下: 第一步 :下载360免费wifi,设置好用户名和密码 查看360免费wifi的IP地址,在cmd中输入ipconfig,我的360IP是 172.21.205.1,netmask是255.255.0.0,注意这两个地址很重要,关系到树莓派的WIFI配置 第二步:用网线进行树莓派的wifi配置(假如目前你的wif

没有数据线,Wifi也能连接Android真机开发调试!彻底解决“无法识别的USB设备”等数据线连接问题!

我是一个小小的Android Developer,我的手机是Samsung GALAXY SII i9100,也算有点老的机子了吧,估计现在都没几个人在用了,三星专卖店都不卖了.平时不玩什么太大型的游戏的话也完全够用了,并且用于开发调试的话也是不错的机型,所以我也经常在自己的手机上运行调试. 但是最近有点蛋疼的是,不知道是数据线坏了还是电脑还是手机的问题,手机用USB数据线连电脑始终不行,插上去就提示"无法识别的USB设备",不知道大家遇到过没.如下图: 这样的话ADB也根本没办法识别

电脑与安卓系统通过wifi进行adb连接

转载地址:http://www.douban.com/note/208397087/ 具体方法:     1. 手机获取root权限: 2. 手机下载安卓终端应用(例如:Better Terminal) 3. 手机端打开终端应用输入: su setprop service.adb.tcp.port 5555 stop adbd start adbd 4. cmd打开电脑控制台,进入到..\android-sdks\platform-tools目录,输入: adb connect 安卓设备的ip地

android 网络连接 wifi gprs的连接

package com.example.androidday15_network1; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo.State; import android.os.Bundle; import andr

Ubuntu14.04创建无线WiFi,android可以连接上网

作为Ubuntu新手,想通过电脑创建WiFi,让手机可以连接上网. 不下软件配置,其他电脑连接时显示(32)insufficient privilege 且手机连不上 查了好久,一直找不到合适的方法,今天http://blog.csdn.net/gsls200808/article/details/39403215在这里找到了方法,可以使用 不过需要启用管理员账号http://shewolfep.iteye.com/blog/413396 http://os.51cto.com/art/2014

旧手机作为USB无线网卡使用(分享WIFI、蓝牙连接)

首先开启手机的WIFI或者蓝牙功能,建立访问互联网的连接,然后设置-更多-网络共享与便携热点,打开安卓手机USB网络共享功能,即可在计算机上通过手机(无电话卡.数据卡)访问互联网.而且此时手机一直在充电,无需担心电量不够用. 如下图:

Android实现WiFi列表显示与连接

项目需要定制一下Android 4.4的设置界面,今天看一下WiFi部分的实现,首先是效果图: 代码比较简单,主要的功能在WiFiAdmin帮助类中,先看一下WiFiListActivity,代码中做了注释,就不细致说了: package com.tchip.carlauncher.ui.activity; import java.util.ArrayList; import java.util.List; import com.tchip.carlauncher.Constant; impor

ubuntu 14.04 无线wifi搜索不到信号

最近买了台新电脑,thinkpad e431,装了win8+ubuntu双系统, ubuntu发现wifi无法搜索到信号,最终解决, 运行一下2个命令: 1.sudo atp-get update 2.sudo atp-get install bcmwl-kernel-source ok!