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

目录
相关文章
|
2月前
|
存储 弹性计算 运维
阿里云国际Windows操作系统迁移教程
阿里云国际Windows操作系统迁移教程
|
28天前
|
安全 搜索推荐 网络安全
Windows操作系统的演变与未来趋势####
本文将深入探讨Windows操作系统从诞生至今的发展历程,分析其关键版本的技术创新、市场影响及用户反馈。同时,结合当前科技趋势,预测Windows系统的未来发展方向,包括智能化、云集成、安全性提升等方面的可能性。 ####
|
1月前
|
NoSQL Linux PHP
如何在不同操作系统上安装 Redis 服务器,包括 Linux 和 Windows 的具体步骤
本文介绍了如何在不同操作系统上安装 Redis 服务器,包括 Linux 和 Windows 的具体步骤。接着,对比了两种常用的 PHP Redis 客户端扩展:PhpRedis 和 Predis,详细说明了它们的安装方法及优缺点。最后,提供了使用 PhpRedis 和 Predis 在 PHP 中连接 Redis 服务器及进行字符串、列表、集合和哈希等数据类型的基本操作示例。
59 4
|
2月前
|
Unix Linux iOS开发
【换行符】Windows、Unix、Mac不同操作系统的回车符\r和换行符\n
【换行符】Windows、Unix、Mac不同操作系统的回车符\r和换行符\n
|
3月前
|
Windows
Windows操作系统部署安装Kerberos客户端
详细介绍了在Windows操作系统上部署安装Kerberos客户端的完整过程,包括下载安装包、安装步骤、自定义安装路径、修改环境变量、配置hosts文件和Kerberos配置文件,以及安装后的验证步骤。
424 3
Windows操作系统部署安装Kerberos客户端
|
5月前
|
IDE Java 开发工具
如何在Windows操作系统上安装PyCharm?
【7月更文挑战第5天】如何在Windows操作系统上安装PyCharm?
210 59
|
4月前
|
Windows
Windows操作系统中环境变量的检索顺序
Windows操作系统中环境变量的检索顺序
129 3
|
4月前
|
Kubernetes Cloud Native 开发者
探索云原生技术:Kubernetes入门与实践探索Windows操作系统的隐藏功能
【8月更文挑战第31天】在数字化转型的浪潮中,云原生技术成为企业提升敏捷性、效率和可靠性的关键。本文将带你了解云原生的核心组件之一——Kubernetes(K8s),通过浅显易懂的语言和实际代码示例,引导你步入这一强大工具的世界。无论你是初学者还是有经验的开发者,本篇都将为你打开一扇通向高效资源管理与自动化部署的大门。
|
4月前
|
负载均衡 网络协议 安全
【Azure 应用服务】Azure Web App的服务(基于Windows 操作系统部署)在被安全漏洞扫描时发现了TCP timestamps漏洞
【Azure 应用服务】Azure Web App的服务(基于Windows 操作系统部署)在被安全漏洞扫描时发现了TCP timestamps漏洞
|
4月前
|
网络协议 应用服务中间件 nginx
性能提升-如何设置Windows操作系统TIME_WAIT状态的TCP连接快速回收时间?
性能提升-如何设置Windows操作系统TIME_WAIT状态的TCP连接快速回收时间?
138 0