Estoy haciendo una práctica donde me piden hacer un Escaneado de red local y que en Datagridview muestre todas las IP tantos las activas y las inactivas, he buscado como hacerlo pero no les entiendo.
Pero me falta tener cual es la red en la que esta conectado el equipo y escanear la red todas sus ip y mostrarlo en un datagridview.
Este es el código que tengo en una clase llamada DeviceInfo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.Net.NetworkInformation;
namespace RedMonIpScanner
{
public static class SubnetMask
{
public static readonly IPAddress ClassA = IPAddress.Parse("255.0.0.0");
public static readonly IPAddress ClassB = IPAddress.Parse("255.255.0.0");
public static readonly IPAddress ClassC = IPAddress.Parse("255.255.255.0");
public static IPAddress CreateByHostBitLength(int hostpartLength)
{
int hostPartLength = hostpartLength;
int netPartLength = 32 - hostPartLength;
if (netPartLength < 2)
throw new ArgumentException("Number of hosts is to large for IPv4");
Byte[] binaryMask = new byte[4];
for (int i = 0; i < 4; i++)
{
if (i * 8 + 8 <= netPartLength)
binaryMask[i] = (byte)255;
else if (i * 8 > netPartLength)
binaryMask[i] = (byte)0;
else
{
int oneLength = netPartLength - i * 8;
string binaryDigit =
String.Empty.PadLeft(oneLength, '1').PadRight(8, '0');
binaryMask[i] = Convert.ToByte(binaryDigit, 2);
}
}
return new IPAddress(binaryMask);
}
public static IPAddress CreateByNetBitLength(int netpartLength)
{
int hostPartLength = 32 - netpartLength;
return CreateByHostBitLength(hostPartLength);
}
public static IPAddress CreateByHostNumber(int numberOfHosts)
{
int maxNumber = numberOfHosts + 1;
string b = Convert.ToString(maxNumber, 2);
return CreateByHostBitLength(b.Length);
}
}
public static class IPAddressExtensions
{
public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] ipAdressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
}
return new IPAddress(broadcastAddress);
}
public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] ipAdressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
}
return new IPAddress(broadcastAddress);
}
public static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask)
{
IPAddress network1 = address.GetNetworkAddress(subnetMask);
IPAddress network2 = address2.GetNetworkAddress(subnetMask);
return network1.Equals(network2);
}
}
public class DeviceInfo
{
public static ArrayList GetMacAddress()
{
// Contador para un ciclo
int i = 0;
// Colección de direcciones MAC
ArrayList DireccionesMAC = new ArrayList();
// Información de las tarjetas de red
NetworkInterface[] interfaces = null;
// Obtener todas las interfaces de red de la PC
interfaces = NetworkInterface.GetAllNetworkInterfaces();
// Validar la cantidad de tarjetas de red que tiene
if (interfaces != null && interfaces.Length > 0)
{
// Recorrer todas las interfaces de red
foreach (NetworkInterface adaptador in interfaces)
{
// Obtener la dirección fisica
PhysicalAddress direccion = adaptador.GetPhysicalAddress();
// Obtener en modo de arreglo de bytes la dirección
byte[] bytes = direccion.GetAddressBytes();
// Variable que tendra la dirección visible
string mac_address = string.Empty;
// Recorrer todos los bytes de la direccion
for (i = 0; i < bytes.Length; i++)
{
// Pasar el byte a un formato legible para el usuario
mac_address += bytes[i].ToString("X2");
if (i != bytes.Length - 1)
{
// Agregar un separador, por formato
mac_address += "-";
}
}
// Agregar la direccion MAC a la lista
DireccionesMAC.Add(mac_address);
}
}
// Valor de retorno, la lista de direcciones MAC
return DireccionesMAC;
}
}
}
Y este es el código que tengo en mi form1 donde mando a llamar las funciones de mi clase:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Net.NetworkInformation; //Para tener alcance a la Clase Ping
using System.IO; //Para el manejo de archivos
namespace RedMonIpScanner
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string hostName = Dns.GetHostName();
string myIP = Dns.GetHostEntry(hostName).AddressList.Where(a => a.IsIPv6LinkLocal == false).FirstOrDefault().ToString();
string submask = SubnetMask.CreateByHostBitLength(myIP.Length).ToString();
lblip.Text = myIP;
lblmac.Text = DeviceInfo.GetMacAddress()[0].ToString();
lblmask.Text = submask;
}
private void Btnescanear_Click(object sender, EventArgs e)
{
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = ComboBox1.SelectedIndex;
Object selectedItem = ComboBox1.SelectedItem;
if (selectedIndex.ToString() == "0" ){
lblseparador.Visible = true;
txtipini.Visible = true;
txtipfin.Visible = true;
}
else if (selectedIndex.ToString() == "1")
{
lblseparador.Visible = false ;
txtipini.Visible = false ;
txtipfin.Visible = false ;
}
//MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
//"Index: " + selectedIndex.ToString());
}
}
}