Windows 10 操作系统下利用USB无限网卡创建虚拟WirelessNetwork 类的封装【二】

简介: 根据前面的一个内容对功能和合理性上做了扩充和优化。代码如下:using System;using System.Collections.

根据前面的一个内容对功能和合理性上做了扩充和优化。

代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace K12NewSmartLesson.PlatForm
{
    public class VWirelessNetworkManager
    {
        private bool isEnableDynamicKey = false;
        private string cleartextKey = null;

        public event EventHandler<VWirelessNetworkEventArgs> VWirelessStarted;
        public event EventHandler<VWirelessNetworkEventArgs> VWirelessStopped;
        public event EventHandler<VWirelessNetworkEventArgs> VWirelessSetted;
        public event EventHandler<VWirelessNetworkEventArgs> VWirelessDisallowed;
        public event EventHandler<VWirelessNetworkEventArgs> VWirelessAllowed;
        public delegate bool VWirelessNetworkCheckHandler(object sender, VWirelessNetworkCheckEventArgs e);
        public event VWirelessNetworkCheckHandler VWirelessChecking;
        private static readonly Process currentProcess = null;
        private static Process CurrentProcess { get; }
        private static bool isRunNetsh = true;
        private static bool isExitNetsh = false;

        /// <summary>
        /// 虚拟无线网络信息
        /// </summary>
        public VWirelessNetwork VWirelessNetworkInfo
        {
            get { return this.GetVWirelessNetwork(); }
        }

        static VWirelessNetworkManager()
        {
            currentProcess = new Process();
            currentProcess.StartInfo = new ProcessStartInfo()
            {
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                FileName = "netsh"
            };
            currentProcess.Start();
        }

        private bool RunNetsh()
        {
            if (!isRunNetsh)
            {
                isRunNetsh = true;
                isExitNetsh = false;
                currentProcess.Start();
            }
            return isRunNetsh;
        }

        private bool ExitNetsh()
        {
            if (!isExitNetsh)
            {
                currentProcess.StandardInput.WriteLine("exit");
                isRunNetsh = false;
                isExitNetsh = true;
            }
            return isExitNetsh;
        }

        public void SetVWirelessNetworkInfo(string sSID)
        {
            string encryptPlus;
            string key = GetDynamicVWirelessKey(sSID, out encryptPlus);
            SetVWirelessNetworkInfo(sSID, key, true);
        }

        public void SetVWirelessNetworkInfo(string sSID, string key)
        {
            SetVWirelessNetworkInfo(sSID, key, false);
        }

        public void SetVWirelessNetworkInfo(string sSID, string key, bool isEnableDynamicKey)
        {
            this.cleartextKey = key;
            this.isEnableDynamicKey = isEnableDynamicKey;
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine(string.Format("wlan set hostednetwork mode=allow ssid={0} key={1}", sSID, key));
            ExitNetsh();
            VWirelessNetworkEventArgs e = new PlatForm.VWirelessNetworkEventArgs();
            e.CommandExecutedResult = currentProcess.StandardOutput.ReadToEnd();
            e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
            OnVWirelessSetted(e);
        }

        public void StartVWirelessNetwork()
        {
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine("wlan start hostednetwork");
            ExitNetsh();
            VWirelessNetworkEventArgs e = new PlatForm.VWirelessNetworkEventArgs();
            e.CommandExecutedResult = currentProcess.StandardOutput.ReadToEnd();
            e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
            e.IPAddress = GetIPV4Address();
            OnVWirelessStarted(e);
        }

        public void StopVWirelessNetwork()
        {
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine("wlan stop hostednetwork");
            ExitNetsh();
            VWirelessNetworkEventArgs e = new PlatForm.VWirelessNetworkEventArgs();
            e.CommandExecutedResult = currentProcess.StandardOutput.ReadToEnd();
            e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
            OnVWirelessStopped(e);
        }

        public void DisallowVWirelessNetwork()
        {
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine("wlan set hostednetwork mode=disallow");
            ExitNetsh();
            VWirelessNetworkEventArgs e = new PlatForm.VWirelessNetworkEventArgs();
            e.CommandExecutedResult = currentProcess.StandardOutput.ReadToEnd();
            e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
            this.OnVWirelessDisallowed(e);
        }

        public void AllowVWirelessNetwork()
        {
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine("wlan set hostednetwork mode=allow");
            ExitNetsh();
            VWirelessNetworkEventArgs e = new PlatForm.VWirelessNetworkEventArgs();
            e.CommandExecutedResult = currentProcess.StandardOutput.ReadToEnd();
            e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
            this.OnVWirelessAllowed(e);
        }
 
        public bool CheckVWirelessNetwork()
        {
            bool isCheckSuccess = false;
            while (true)
            {
                VWirelessNetworkCheckEventArgs e = new VWirelessNetworkCheckEventArgs(new List<string>());
                e.VWirelessNetworkShowInfo = GetVWirelessNetwork();
                if (e.VWirelessNetworkShowInfo.BearerNetworkSettings.Mode == "已禁用")
                {
                    e.ErrorTexts.Add("虚拟无线网络被禁用,请使用 this.AllowVWirelessNetwork(); 设置为允许。");
                }
                NetworkInterface vNetwork = this.GetMicrosoftHostedNetworkVirtualAdapter();
                if (vNetwork == null)
                {
                    e.ErrorTexts.Add("未能检测到本地计算机安装USB无线网卡");
                }
                if (e.ErrorTexts.Count == 0)
                {
                    e.IPAddress = GetIPV4Address();
                    isCheckSuccess = true;
                }
                if (!OnVWirelessChecking(e))
                {
                    break;
                }
            }
            return isCheckSuccess;
        }

        public string GetIPV4Address()
        {

            string iPV4Address = null;
            //获取虚拟无限网络的IPV4地址
            NetworkInterface vNetwork = GetMicrosoftHostedNetworkVirtualAdapter();
            UnicastIPAddressInformationCollection ipCollection = vNetwork.GetIPProperties().UnicastAddresses;
            if (ipCollection.Count > 1)
            {
                iPV4Address = ipCollection[1].Address.ToString();
            }
            else
            {
                iPV4Address = ipCollection[0].Address.ToString();
            }
            return iPV4Address;
        }

        public string GetIPV6Address()
        {
            string iPV6Address = null;
            //获取虚拟无限网络的IPV4地址
            NetworkInterface vNetwork = GetMicrosoftHostedNetworkVirtualAdapter();
            UnicastIPAddressInformationCollection ipCollection = vNetwork.GetIPProperties().UnicastAddresses;
            if (ipCollection.Count > 1)
            {
                iPV6Address = ipCollection[0].Address.ToString();
            }
            return iPV6Address;
        }

        public NetworkInterface GetMicrosoftHostedNetworkVirtualAdapter()
        {
            return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(w => w.Description == "Microsoft Hosted Network Virtual Adapter" && w.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
        }

        protected virtual VWirelessNetwork GetVWirelessNetwork()
        {
            RunNetsh();
            currentProcess.StandardInput.AutoFlush = true;
            currentProcess.StandardInput.WriteLine("wlan show hostednetwork");
            ExitNetsh();
            VWirelessNetwork vWNInfo = new VWirelessNetwork();
            vWNInfo.IsEnableDynamicKey = isEnableDynamicKey;
            vWNInfo.RawVWirelessNetworkShowInfo = currentProcess.StandardOutput.ReadToEnd();
            string[] kvpItems = vWNInfo.RawVWirelessNetworkShowInfo.Split(new char[] { '\r', '\n' });
            if (kvpItems.Length > 14)
            {
                vWNInfo.BearerNetworkSettings = new PlatForm.BearerNetworkSettings()
                {
                    Mode = kvpItems[6].Split(':')[1].Trim(),
                    SSID = kvpItems[8].Split(':')[1].Trim().Trim(new char[] { '“', '”' }),
                    MaxClientQuantity = int.Parse(kvpItems[10].Split(':')[1]),
                    Authentication = kvpItems[12].Split(':')[1].Trim(),
                    Key = this.isEnableDynamicKey ? kvpItems[14].Split(':')[1].Trim() : this.cleartextKey
                };
                vWNInfo.BearerNetworkStatus = new BearerNetworkStatus();
                string status = kvpItems[22].Split(':')[1].Trim();
                vWNInfo.BearerNetworkStatus.Status = status;
                if (status == "已启动")
                {
                    vWNInfo.BearerNetworkStatus.BSSID = kvpItems[24].Substring(28, 17);
                    vWNInfo.BearerNetworkStatus.WirelessType = kvpItems[26].Split(':')[1].Trim();
                    vWNInfo.BearerNetworkStatus.Channels = int.Parse(kvpItems[28].Split(':')[1]);
                    int clientQuantity = int.Parse(kvpItems[30].Split(':')[1]);
                    vWNInfo.BearerNetworkStatus.ClientQuantity = clientQuantity;


                    if (clientQuantity > 0)
                    {
                        for (int i = 1; i <= clientQuantity; i++)
                        {
                            vWNInfo.BearerNetworkStatus.Clients.Add(kvpItems[30 + i * 2].TrimStart().Substring(0, 17));
                        }
                    }
                }
            }
            return vWNInfo;
        }


        protected virtual void OnVWirelessSetted(VWirelessNetworkEventArgs e)
        {
            if (VWirelessSetted != null)
            {
                VWirelessSetted(this, e);
            }
        }

        protected virtual void OnVWirelessStarted(VWirelessNetworkEventArgs e)
        {
            if (VWirelessStarted != null)
            {
                VWirelessStarted(this, e);
            }
        }

        protected virtual void OnVWirelessStopped(VWirelessNetworkEventArgs e)
        {
            if (VWirelessStopped != null)
            {
                VWirelessStopped(this, e);
            }
        }

        protected virtual void OnVWirelessDisallowed(VWirelessNetworkEventArgs e)
        {
            if (VWirelessDisallowed != null)
            {
                VWirelessDisallowed(this, e);
            }
        }

        protected virtual void OnVWirelessAllowed(VWirelessNetworkEventArgs e)
        {
            if (VWirelessAllowed != null)
            {
                VWirelessAllowed(this, e);
            }
        }

        protected virtual bool OnVWirelessChecking(VWirelessNetworkCheckEventArgs e)
        {
            bool isContinueLoopChecking = true;
            if (VWirelessChecking != null)
            {
                isContinueLoopChecking = VWirelessChecking(this, e);
            }
            return isContinueLoopChecking;
        }

        private static string GetDynamicVWirelessKey(string sSID, out string encryptPlus)
        {
            string encrypedSSID = GetHashedString32(sSID); ;
            string head = null;
            string tail = null;
            encryptPlus = Guid.NewGuid().ToString();
            char[] chars = encryptPlus.ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                if (i % 2 == 0)
                {
                    head += chars[i];
                }
                else
                {
                    tail += chars[i];
                }
            }
            string waitingEncryptString2 = head + encrypedSSID + tail;
            return GetHashedString32(waitingEncryptString2);
        }

        private static string GetHashedString32(string waitingEncryptString)
        {
            string encrypedString = null;
            byte[] buff = Encoding.UTF8.GetBytes(waitingEncryptString);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBuff = md5.ComputeHash(buff);
            foreach (byte b in encryptedBuff)
            {
                encrypedString += b.ToString("X2");
            }
            return encrypedString;
        }
    }
}

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

namespace K12NewSmartLesson.PlatForm
{
    /// <summary>
    /// 虚拟无线网络事件参数
    /// </summary>
    public class VWirelessNetworkEventArgs : EventArgs
    {
        /// <summary>
        /// 命令执行后的结果
        /// </summary>
        public string CommandExecutedResult { get; set; }
        /// <summary>
        /// 虚拟无限网络的IP地址
        /// </summary>
        public string IPAddress { get; set; }
        /// <summary>
        /// 显示虚拟无线网络信息
        /// </summary>
        public VWirelessNetwork VWirelessNetworkShowInfo { get; set; }
    }

    /// <summary>
    /// 验证虚拟无线网络是否可用事件参数
    /// </summary>
    public class VWirelessNetworkCheckEventArgs : VWirelessNetworkEventArgs
    {
        /// <summary>
        /// 出错文本信息列表字段
        /// </summary>
        private IList<string> errorTexts;

        /// <summary>
        /// 初始化验证虚拟无线网络是否可用事件参数的实例
        /// </summary>
        /// <param name="errorTexts">出错文本信息列表</param>
        public VWirelessNetworkCheckEventArgs(IList<string> errorTexts)
        {
            this.errorTexts = errorTexts;
        }

        /// <summary>
        /// 出错文本信息列表
        /// </summary>
        public IList<string> ErrorTexts
        {
            get
            {
                return errorTexts;
            }
        }
    }

    /// <summary>
    /// 虚拟无线网络信息
    /// </summary>
    public class VWirelessNetwork
    {
        /// <summary>
        /// 显示虚拟无线网络原始信息
        /// </summary>
        public string RawVWirelessNetworkShowInfo { get; set; }
        /// <summary>
        /// 是否启用虚拟无限网络动态生成密码
        /// </summary>
        public bool IsEnableDynamicKey { get; set; }
        /// <summary>
        /// 承载虚拟无线网络设置
        /// </summary>
        public BearerNetworkSettings BearerNetworkSettings { get; set; }
        /// <summary>
        /// 承载虚拟无线网络状态
        /// </summary>
        public BearerNetworkStatus BearerNetworkStatus { get; set; }
    }

    /// <summary>
    /// 承载网络设置
    /// </summary>
    public class BearerNetworkSettings
    {
        /// <summary>
        /// 模式
        /// </summary>
        public string Mode { get; set; }
        /// <summary>
        /// SSID 名称
        /// </summary>
        public string SSID { get; set; }
        /// <summary>
        /// 最多客户端数
        /// </summary>
        public int MaxClientQuantity { get; set; }
        /// <summary>
        /// 身份验证
        /// </summary>
        public string Authentication { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Key { get; set; }
    }

    /// <summary>
    /// 承载网络状态
    /// </summary>
    public class BearerNetworkStatus
    {
        private IList<string> clients = new List<string>();

        /// <summary>
        /// 状态
        /// </summary>
        public string Status { get; set; }
        /// <summary>
        /// BSSID
        /// </summary>
        public string BSSID { get; set; }
        /// <summary>
        /// 无线电类型
        /// </summary>
        public string WirelessType { get; set; }
        /// <summary>
        /// 频道
        /// </summary>
        public int Channels { get; set; }
        /// <summary>
        /// 客户端数
        /// </summary>
        public int ClientQuantity { get; set; }
        /// <summary>
        /// 客户端MAC地址列表
        /// </summary>
        public IList<string> Clients { get { return clients; } }
    }
}

调用端代码如下:

   
VWirelessNetworkManager vwifi;
vwifi = new VWirelessNetworkManager(); vwifi.VWirelessSetted += Vwifi_VWirelessSetted; vwifi.VWirelessStarted += Vwifi_VWirelessStarted; vwifi.VWirelessStopped += Vwifi_VWirelessStopped; vwifi.VWirelessChecking += Vwifi_VWirelessChecking;
 
 
比较重要的是下面这个是下面这个事件的返回值,他决定了是否一直循环检查虚拟无线网络的是否正常。
private bool Vwifi_VWirelessChecking(object sender, VWirelessNetworkCheckEventArgs e)
        {
            bool isContinueChecking = false;
            if (e.ErrorTexts.Count > 0)
            {
                string topErrorText = string.Format("{0},重试请按确定,退出请按取消,谢谢!", e.ErrorTexts[0]);
                if (MessageBox.Show(topErrorText, "错误", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                {
                    Application.Exit();
                }
                isContinueChecking = true;
            }
            return isContinueChecking;
        }

目录
相关文章
|
Linux 异构计算 Windows
Windows操作系统:指定网卡ping连通性
某些时候,板卡上留有两个及以上万兆网口,在没有其他FPGA板卡或者只是想测一下网口或者万兆光模块的通路时,可以通过回环互ping来验证下连通性
3630 0
|
6月前
|
安全 虚拟化 Windows
手把手教你如何在虚拟机上安装Windows 10
手把手教你如何在虚拟机上安装Windows 10
178 2
|
6月前
|
安全 开发工具 git
Windows11搭建Python环境(2)- Anaconda虚拟环境中安装Git
Windows11搭建Python环境(2)- Anaconda虚拟环境中安装Git
196 0
|
6月前
|
物联网 Windows
安装windows 10操作系统
安装windows 10操作系统
|
6月前
|
存储 监控 网络协议
DP读书:《openEuler操作系统》(九)从IPC到网卡到卡驱动程序
DP读书:《openEuler操作系统》(九)从IPC到网卡到卡驱动程序
135 4
|
6月前
|
监控 Unix Linux
在Linux和类Unix操作系统中,`top` 命令
在Linux和类Unix操作系统中,`top` 命令
65 2
|
Shell 网络安全 网络虚拟化
[笔记]Windows使用OpenVpn构建虚拟局域网
[笔记]Windows使用OpenVpn构建虚拟局域网
604 0
|
存储 Python Windows
windows创建python虚拟环境
本文有2种创建python虚拟环境的方式, 如果第二种方式有问题, 建议使用第一种方式!
windows创建python虚拟环境
|
编解码 网络协议 Windows
封装操作系统(保姆教程)(下)
封装操作系统(保姆教程)
162 0
|
安全 数据安全/隐私保护 Windows
封装操作系统(保姆教程)(上)
封装操作系统(保姆教程)
228 0