最近因为公司的业务要求,在没有网络的情况下,没有路由器支持的情况下,需要组建一个小局域网,可以同时支持多个终端的相互之间的通信,这里的解决方案如下。
一、硬件要求:任意支持软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();
}
五、说明
最后测试部分的动态密码的意思是提供不公开密码的情况下,根据规则自动计算的,具体方法可以自己修改。
如有其他问题可以留言。