VirtualAP – Utilidad en C# y scripting para crear un Access Point Virtual Wifi en Windows
Posted in HelpDesk, Internet, Networking, Scripting, Sistemas, soporte, Tecnología, Utilidades, virtualización on Oct 24th, 2012
Referencias:
- http://www.practicallynetworked.com/networking/create_a%20virtual_wireless_router_with_windows.htm
- http://www.windowsnetworking.com/kbase/WindowsTips/WindowsServer2008/AdminTips/Network/NewNetshWLANCommandsinWindows7andServer2008R2.html
- http://uhurumkate.blogspot.com.es/2012/06/internet-connection-sharing-ics-scripts.html
- http://www.windowsnetworking.com/articles_tutorials/new-netsh-commands-windows-7-server-2008-r2.html
- https://github.com/drorgl/ForBlog/tree/master/ICS
La utilidad esta escrita en C# 4.0 bajo SharpDevelop 4.2 y compilada para .Net 2.0 y probada en Windows 7
La utilidad debe de ejecutarse con permisos de administrador local
Objetivo de la utilidad:
Crear un punto de acceso wifi virtual en un equipo bajo windows y con una tarjeta de red wireless (nic wifi)
para dar acceso a la red local y a Internet a los dispositivos wifi del usuario.
La mecanica de la utilidad:
Lo primero es parametrizar el SSID del AP y la clave de acceso WPA2 personal e iniciar el proceso con el botón “iniciar AP”.
Que creara el Microsoft Virtual Wifi Miniport Adapter, sino existiese, e iniciará el modo de red hospedada en modo permitir con su ssid y su key wpa2
Tras esto deberemos elegir la conexión de red que tenga acceso a Internet y que queramos compartir con nuestro AP
Si deseamos acceder a Internet desde la red local wifi creada con el AP, elegimos la conexión de red que disponga de Internet y pulsamos compartir internet
Nos saldran un par de mensajes del script ics.vbs
Y ya tendriamos el AP wifi virtual operativo y con acceso a internet para los clientes que se conecten al mismo.
Por defecto MiSSID sera el SSID de mi AP virtual y 123456789 mi clave de acceso WPA2 personal.
Un cliente wifi, via dhcp, al conectarse a nuestro AP virtual recibirá una IP,mascara (usualmente en la red 192.168.137.0/24), gateway y dns (gw y dns suelen ser 192.168.137.1).
Y tras esto podras conectarte a tu AP virtual desde otro host y tener acceso a Inet.
Si pulsamos el boton info tendremos información de la configuración de la red hospedada y la salida de ipconfig /all
Configuraci¢n de red hospedada
——————————
Modo: permitido
Nombre de SSID : “MiSSID”
N§ m ximo de clientes : 100
Autenticaci¢n : WPA2-Personal
Cifrado : CCMPEstado de la red hospedada
————————–
Estado : Iniciado
BSSID : 06:11:76:88:e2:84
Tipo de radio : 802.11g
Canal : 11
N£mero de clientes : 0Configuraci¢n IP de Windows
Nombre de host. . . . . . . . . : cpu
Sufijo DNS principal . . . . . :
Tipo de nodo. . . . . . . . . . : h¡brido
Enrutamiento IP habilitado. . . : no
Proxy WINS habilitado . . . . . : noAdaptador de LAN inal mbrica Conexi¢n de red inal mbrica 2:
Sufijo DNS espec¡fico para la conexi¢n. . :
Descripci¢n . . . . . . . . . . . . . . . : Microsoft Virtual WiFi Miniport Adapter #2
Direcci¢n f¡sica. . . . . . . . . . . . . : 06-11-77-88-E8-82
DHCP habilitado . . . . . . . . . . . . . : no
Configuraci¢n autom tica habilitada . . . : s¡
Direcci¢n IPv4. . . . . . . . . . . . . . : 192.168.137.1(Preferido)
M scara de subred . . . . . . . . . . . . : 255.255.255.0
Puerta de enlace predeterminada . . . . . :
NetBIOS sobre TCP/IP. . . . . . . . . . . : habilitado
Para para el AP , pusar el boton parar.
El código del MainForm.cs
/*
* Created by SharpDevelop.
* User: JavCasta - 2.012 - http://javcasta.com/
* Date: 10/10/2012
* Time: 10:10
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Diagnostics;
using System.Drawing;
using System.Management;
using System.Threading;
using System.Windows.Forms;
using NETCONLib;
using NetFwTypeLib;
namespace virtualAP
{
///
<summary> /// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
//obtenemos conexiones de red
misConexiones();
if (comprobar()) {};
}
void Button1Click(object sender, EventArgs e)
{
//comenzar
Cursor.Current = Cursors.WaitCursor;
orden("netsh wlan set hostednetwork mode=allow ssid="+textBox1.Text+" key="+textBox2.Text);
if (!comprobar())
{
Cursor.Current = Cursors.Default;
MessageBox.Show("Error: no se puede crear el Microsoft Virtual Wifi Miniport adapter");
}
else
{
progressBar1.Style = ProgressBarStyle.Marquee;
orden("netsh wlan start hostednetwork");
button5.Enabled = true;
}
}
public bool comprobar() {
//progressBar1.Style = ProgressBarStyle.Marquee;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapter");
foreach (ManagementObject mo in mc.GetInstances())
{
int index = Convert.ToInt32(mo["Index"]);
string nombre = mo["Name"] as string;
string name = mo["NetConnectionID"] as string;
if (!string.IsNullOrEmpty(nombre) && !string.IsNullOrEmpty(name))
{
if (nombre.StartsWith("Microsoft Virtual WiFi Miniport Adapter"))
{
textBox3.Text = name.ToString();
comboBox1.Items.Remove(name.ToString());
comboBox1.Refresh();
textBox3.Visible = true;
label3.Visible = true;
return true;
}
}
}
return false;
}
public void misConexiones()
{
//ref http://stackoverflow.com/questions/3457119/how-to-get-default-nic-connection-name
ManagementClass mc = new ManagementClass("Win32_NetworkAdapter");
foreach (ManagementObject mo in mc.GetInstances())
{
int index = Convert.ToInt32(mo["Index"]);
string name = mo["NetConnectionID"] as string;
if (!string.IsNullOrEmpty(name))
{
comboBox1.Items.Add(name);
}
}
comboBox1.Text = "Elegir conexión de red a compartir Internet";
}
public void orden(string comando)
{
string strCmdLine = comando;
ProcessStartInfo shell = new ProcessStartInfo(@"cmd.exe", "/c " + strCmdLine );
shell.UseShellExecute = false;
shell.RedirectStandardOutput = true;
shell.RedirectStandardError = true;
shell.CreateNoWindow = true;
Process unProceso = new Process();
unProceso.StartInfo = shell;
unProceso.Start();
string output = unProceso.StandardOutput.ReadToEnd();
richTextBox1.Text += output;
richTextBox1.Select(richTextBox1.Text.Length - 1, richTextBox1.Text.Length - 1);
richTextBox1.AppendText("");
richTextBox1.ScrollToCaret();
unProceso.WaitForExit();
}
void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
{
richTextBox1.Text += "Se compartira Inet de la conexion: " + comboBox1.Text + "\r\n"
+ " con la conexion: " + textBox3.Text + "\r\n";
}
void Button2Click(object sender, EventArgs e)
{
orden("netsh wlan stop hostednetwork");
orden("netsh wlan set hostednetwork mode=disallow");
textBox3.Visible = false;
label3.Visible = false;
button5.Enabled = false;
Cursor.Current = Cursors.Default;
progressBar1.Style = ProgressBarStyle.Blocks;
}
void Button3Click(object sender, EventArgs e)
{
orden("netsh wlan show hostednetwork");
orden("ipconfig /all");
}
void Button4Click(object sender, EventArgs e)
{
Process.Start("http://javcasta.com");
}
void Button5Click(object sender, EventArgs e)
{
//compartir internet
if (textBox3.Visible && !comboBox1.Text.Equals("Elegir conexión de red a compartir Internet"))
{
//compartir inet via script en vbs de Dror Gluska (2012) - http://uhurumkate.blogspot.co.il/
// ref: https://github.com/drorgl/ForBlog/tree/master/ICS
//Nos aseguramos que el servicio ICS (SharedAccess) se inicie
orden("sc start SharedAccess");
//compartimos conexion de combobox con textbox3 : true
string torden="ics.vbs " +"\""+comboBox1.Text +"\""+ " " + "\""+textBox3.Text +"\""+ " true";
orden(torden);
}
else MessageBox.Show("Elija conexión de red a compartir Internet \r\n o No hay conexion virtual con la que compartir Inet");
}
}
}
El codigo del script ics.vbs (que se encarga de la parte de compartir Internet) de Dror Gluska (2012) – http://uhurumkate.blogspot.co.il/ lo podeis encontrar en:
https://github.com/drorgl/ForBlog/tree/master/ICS
Y voila
























