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

简介: 最近因为公司的业务要求,在没有网络的情况下,没有路由器支持的情况下,需要组建一个小局域网,可以同时支持多个终端的相互之间的通信,这里的解决方案如下。

最近因为公司的业务要求,在没有网络的情况下,没有路由器支持的情况下,需要组建一个小局域网,可以同时支持多个终端的相互之间的通信,这里的解决方案如下。


一、硬件要求:任意支持软AP的无限网卡,具体是否支持请输入命令行如下查看,如图(一):


图(一)

根据上图,包含 C:\Windows\system32\DRIVERS\vwifibus.sys即可支持软AP。

二、熟悉命令

1.设置并允许虚拟无线网路;

命令:netsh 命令符下输入 wlan set hostednetwork mode = allow ssid=无线名称 key=无线密码(8位数)

返回结果:承载网络模式已设置为允许。
已成功更改承载网络的 SSID。
已成功更改托管网络的用户密钥密码。


2.显示设置的虚拟网络信息;

命令:netsh 命令符下输入 wlan show hostednetwork

返回结果:承载网络设置
-----------------------
    模式                   : 已启用
    SSID 名称              :“无线名称”
    最多客户端数  : 32
    身份验证         : WPA2 - 个人
    密码                 : CCMP


承载网络状态
---------------------
    状态                 : 未启动


netsh>


3.启动设置的无线网络

命令:netsh 命令符下输入 wlan start hostednetwork


4.停止设置的无线网络

命令:netsh 命令符下输入 wlan stop hostednetwork


5.禁止设置的无线网络

命令:命令:netsh 命令符下输入 wlan set hostednetwork mode=disallow

返回结果:承载网络模式已设置为禁止。


三、对应封装的C#类,代码如下:

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;

        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"
                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 SetVWirelessInfo(string sSID)
        {
            string encryptPlus;
            string key = GetDynamicVWirelessKey(sSID, out encryptPlus);
            SetVWirelessInfo(sSID, key, true);
        }

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

        public void SetVWirelessInfo(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 StartVWirelessNet()
        {
            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 = GetIpAddress();
            OnVWirelessStarted(e);
        }

        public void StopVWirelessNet()
        {
            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 DisallowVWirelessNet()
        {
            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();
        }


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

        public string GetIpAddress()
        {
            string ipV4Address = null;
            //获取虚拟无限网络的IPV4地址
            NetworkInterface vNetwork = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(w => w.Description == "Microsoft Hosted Network Virtual Adapter" && w.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
            UnicastIPAddressInformationCollection ipCollection = vNetwork.GetIPProperties().UnicastAddresses;
            if (ipCollection.Count > 1)
            {
                ipV4Address = ipCollection[1].Address.ToString();
            }
            else
            {
                ipV4Address = ipCollection[0].Address.ToString();
            }
            return ipV4Address;
        }

        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 OnVWirelessSetted(VWirelessNetworkEventArgs e)
        {
            if (VWirelessSetted != null)
            {
                VWirelessSetted(this, e);
            }
        }

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

 /// <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 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 = null;
  vwifi = new VWirelessNetworkManager();
            vwifi.VWirelessSetted += Vwifi_VWirelessSetted;
            vwifi.VWirelessStarted += Vwifi_VWirelessStarted;
            vwifi.VWirelessStopped += Vwifi_VWirelessStopped;

 /// <summary>
        /// 窗口加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmShowNetInfo_Load(object sender, EventArgs e)
        {
            //this.lstboxMessage.Items.Add("消息:正在启动应用程序!");
            RunatVWirelessNetwork();
        }

        private void RunatVWirelessNetwork()
        {
            // this.lstboxMessage.Items.Add("消息:正在检测是否安装USB版本的无限网卡!");
            if (CheckWirelessCard())
            {
                // this.lstboxMessage.Items.Add("消息:检测已经安装USB版本的无限网卡!");
                if (GlobalConfig.AppSettings.VWirelessNetwork.IsEnableDynamicKey)
                {
                    //this.lstboxMessage.Items.Add("消息:动态生成密码功能已开启,以规则运算方式并创建虚拟无限网络!");
                    vwifi.SetVWirelessInfo(string.Format("SmTR-{0}", DateTime.Now.ToString("HHmmssfffffff")));
                }
                else
                {
                    //this.lstboxMessage.Items.Add("消息:动态生成密码功能未开启,以明文密码方式并创建虚拟无限网络!");
                    vwifi.SetVWirelessInfo(string.Format("SmTR-{0}", DateTime.Now.ToString("HHmmssfffffff")), DateTime.Now.ToOADate().ToString());
                }
                //this.lstboxMessage.Items.Add("消息:正在启动虚拟无限网络!");
                vwifi.StartVWirelessNet();
            }
            else
            {
                Application.Exit();
            }

五、说明

最后测试部分的动态密码的意思是提供不公开密码的情况下,根据规则自动计算的,具体方法可以自己修改。

如有其他问题可以留言。




目录
相关文章
|
20天前
|
存储 弹性计算 运维
阿里云国际Windows操作系统迁移教程
阿里云国际Windows操作系统迁移教程
|
29天前
|
Unix Linux iOS开发
【换行符】Windows、Unix、Mac不同操作系统的回车符\r和换行符\n
【换行符】Windows、Unix、Mac不同操作系统的回车符\r和换行符\n
|
2月前
|
Windows
Windows操作系统部署安装Kerberos客户端
详细介绍了在Windows操作系统上部署安装Kerberos客户端的完整过程,包括下载安装包、安装步骤、自定义安装路径、修改环境变量、配置hosts文件和Kerberos配置文件,以及安装后的验证步骤。
283 3
Windows操作系统部署安装Kerberos客户端
|
4月前
|
IDE Java 开发工具
如何在Windows操作系统上安装PyCharm?
【7月更文挑战第5天】如何在Windows操作系统上安装PyCharm?
190 59
|
3月前
|
Windows
Windows操作系统中环境变量的检索顺序
Windows操作系统中环境变量的检索顺序
91 3
|
3月前
|
Kubernetes Cloud Native 开发者
探索云原生技术:Kubernetes入门与实践探索Windows操作系统的隐藏功能
【8月更文挑战第31天】在数字化转型的浪潮中,云原生技术成为企业提升敏捷性、效率和可靠性的关键。本文将带你了解云原生的核心组件之一——Kubernetes(K8s),通过浅显易懂的语言和实际代码示例,引导你步入这一强大工具的世界。无论你是初学者还是有经验的开发者,本篇都将为你打开一扇通向高效资源管理与自动化部署的大门。
|
3月前
|
负载均衡 网络协议 安全
【Azure 应用服务】Azure Web App的服务(基于Windows 操作系统部署)在被安全漏洞扫描时发现了TCP timestamps漏洞
【Azure 应用服务】Azure Web App的服务(基于Windows 操作系统部署)在被安全漏洞扫描时发现了TCP timestamps漏洞
|
3月前
|
网络协议 应用服务中间件 nginx
性能提升-如何设置Windows操作系统TIME_WAIT状态的TCP连接快速回收时间?
性能提升-如何设置Windows操作系统TIME_WAIT状态的TCP连接快速回收时间?
95 0
|
4月前
|
算法 UED
深入理解操作系统:虚拟内存管理机制
【7月更文挑战第4天】在数字时代的浪潮中,操作系统的虚拟内存管理机制如同一座精巧的时间桥梁,连接着有限的物理资源与无限的程序需求。本文将揭开这座桥梁的秘密,从虚拟内存的基本概念出发,逐步深入到页面置换算法的世界,探讨它们如何影响系统性能和用户体验。通过对比分析不同的页面置换策略,我们旨在为读者提供一种全新的视角,以理解和评估现代操作系统中这一至关重要的功能。
55 1
|
4月前
|
Windows 内存技术
nvm 管理和切换 node版本(windows操作系统)
nvm 管理和切换 node版本(windows操作系统)
80 0