0

hola estoy haciendo una aplicacion en C# para escritorio, se ve sencillo pero se me complica mucho por que apenas estoy aprendiendo este lenguaje.

Este es la clase que tengo:

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

    }

y quiero llamar cada uno de ella en un label pero algo me falta o tengo mal que no he logrado hacerlo.

private void Form1_Load(object sender, EventArgs e)
        {
            string hostName = Dns.GetHostName();
            string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
            lblip.Text = myIP;

            lblmac.Text = DeviceInfo.GetMacAddress()[0].ToString();
            **lblmask.Text = SubnetMask.CreateByHostBitLength();**esta es la que no sale
        }

alguien me puede ayudar, lo que trato de hacer es una aplicacion de escanear la red y que me la ip, mascara y mac. Hasta el momento ya tengo la ip y la MAC, lo que estoy batallando es en mostrar la mascara de subred y la red principal el cual esta conectado el equipo.

1 respuesta 1

1

Adiciona este using:

using System.Linq; 

Luego verifica este

public void GetNetworkInfo()
{
      string hostName = Dns.GetHostName();

      //aqui uso la función GetHostEntry porque GetHostName está en desuso lo que significa que en una actualización podría dejar de funcionar.

      string myIP = Dns.GetHostEntry(hostName).AddressList.Where(a => a.IsIPv6LinkLocal == false).FirstOrDefault().ToString();

       string macAddress = GetMACAddress();
       //corregido
       string submask = SubnetMask.CreateByHostBitLength(myIP.Length).ToString();

       //coloca aquí los sets a tus respectivos labels
       lblip.Text = myIP;
       lblmac.Text = macAddress;
       lblmask.Text = submask;
 }

Como alternativa opcional puedes utilizar esta función para obtener la MAC address:

 public string GetMACAddress()
 {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            string sMacAddress = string.Empty;

            foreach (NetworkInterface adapter in nics)
            {
                if (sMacAddress == string.Empty)// only return MAC Address from first card
                {
                    IPInterfaceProperties properties = adapter.GetIPProperties();
                    sMacAddress = adapter.GetPhysicalAddress().ToString();
                }
            }
            return sMacAddress;
        }
6
  • Hola @jtaborga ya realice los cambios pero me marca un error en string submask = SubnetMask.CreateByHostBitLength(myIP.Length); me dice: No se puede convertir implícitamente el tipo 'System.Net.IPAddress' en 'string' el 22 ago. 2019 a las 14:43
  • corregido, revisa nuevamente por favor en esa misma línea el .ToString al final
    – jtaborga
    el 22 ago. 2019 a las 15:48
  • Muchas gracias @jtaborga ya no sale el error, solo que me da una mascara extraña jejejje segun yo la mascara debe ser 255.255.255.0 y me da 255.255.192.0, sera que tengo algo mal en mi función? el 22 ago. 2019 a las 16:02
  • puede ser que esté mal tu función CreateByHostBitLength
    – jtaborga
    el 22 ago. 2019 a las 16:08
  • Marca la respuesta como correcta y crea una nueva pregunta con tu función para que se pueda revisar.
    – jtaborga
    el 22 ago. 2019 a las 16:15

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.