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

目录
相关文章
|
8月前
|
Web App开发 移动开发 Linux
DP读书:《openEuler操作系统》(七)FSCK与VFS虚拟文件系统
DP读书:《openEuler操作系统》(七)FSCK与VFS虚拟文件系统
220 0
|
8月前
|
存储 算法
【操作系统】虚拟存储管理-页面置换算法
【操作系统】虚拟存储管理-页面置换算法
812 0
|
存储
操作系统(5.1)--虚拟储存器
综上所述:程序只要装入内存一部分就可以运行,当用到不在内存的部分时,再将其装入内存。换句话就是说程序全部装入内存并不是程序运行的必要条件。
428 0
|
6月前
|
算法 UED
深入理解操作系统:虚拟内存管理机制
【7月更文挑战第4天】在数字时代的浪潮中,操作系统的虚拟内存管理机制如同一座精巧的时间桥梁,连接着有限的物理资源与无限的程序需求。本文将揭开这座桥梁的秘密,从虚拟内存的基本概念出发,逐步深入到页面置换算法的世界,探讨它们如何影响系统性能和用户体验。通过对比分析不同的页面置换策略,我们旨在为读者提供一种全新的视角,以理解和评估现代操作系统中这一至关重要的功能。
72 1
|
7月前
|
存储 缓存
操作系统的虚拟内存管理机制
在现代计算机系统中,虚拟内存是一种至关重要的内存管理技术。它允许操作系统使用硬盘空间来扩展物理内存容量,从而支持更多并发运行的程序。本文将深入探讨虚拟内存的概念、实现方式以及其在操作系统中的作用和重要性。
|
7月前
|
算法 安全 调度
深入理解操作系统的虚拟内存管理机制
【6月更文挑战第18天】在现代计算机系统中,虚拟内存是实现多任务处理和内存保护的关键技术。本文将深入探讨操作系统如何通过虚拟内存管理机制来优化物理资源的使用,提高系统效率,并确保进程间的隔离与安全。我们将从虚拟内存的基本概念出发,逐步解析分页、分段、内存交换以及页面替换算法等核心组件,揭示它们如何协同工作以支撑起整个系统的内存需求。
117 3
|
6月前
|
算法 安全 UED
深入理解操作系统的虚拟内存管理机制
【7月更文挑战第2天】在现代计算机系统设计中,虚拟内存是实现内存管理高效、安全和可扩展的关键技术。本文将深入探讨虚拟内存的管理机制,包括分页技术、内存分配策略以及页面替换算法等核心概念。通过分析虚拟内存如何优化物理内存的使用,提高系统的运行效率,并讨论其在实际操作系统中的应用和面临的挑战,旨在为读者提供对虚拟内存管理机制的全面理解。
|
8月前
|
存储 算法 安全
探索操作系统的虚拟内存管理机制
【5月更文挑战第28天】在现代操作系统中,虚拟内存管理是一项关键技术,它允许系统使用有限的物理内存资源来模拟更大范围的地址空间。本文将深入剖析虚拟内存的工作原理,包括分页机制、地址转换、页面置换算法以及虚拟内存对系统性能的影响。通过理解这些概念,读者可以更好地掌握操作系统如何有效地管理和分配内存资源。
|
8月前
|
监控 安全 虚拟化
深入浅出:NSSM封装Windows服务工具的使用与介绍
深入浅出:NSSM封装Windows服务工具的使用与介绍
318 3
|
8月前
|
物联网 Windows
安装windows 10操作系统
安装windows 10操作系统