elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Guardar la MAC en una variable.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Guardar la MAC en una variable.  (Leído 3,532 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Guardar la MAC en una variable.
« en: 23 Enero 2016, 15:43 pm »

Hola:

Me falla este programa, quiero coger la MAC de este formato que genera en la primera tarjeta de red física (04-B2-AF-EE-E2-34-6A-8C).

Al complicar, me dale este error.
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. using System.Net.NetworkInformation; // No olvidar.
  8.  
  9. namespace Leer_MAC
  10. {
  11.    class Program
  12.    {
  13.        static void Main(string[] args)
  14.        {
  15.            Console.Title = "En busca del MAC";
  16.  
  17.            string Nombre_HostName = null;
  18.            string Nombre_Dominio = null;
  19.            string MAC = null;
  20.  
  21.            IPGlobalProperties Propiedades_PC = IPGlobalProperties.GetIPGlobalProperties();
  22.            NetworkInterface[] Interfaz_red = NetworkInterface.GetAllNetworkInterfaces();
  23.            Console.WriteLine("Información de interfaz para {0}.{1}     ",
  24.                    Propiedades_PC.HostName, Propiedades_PC.DomainName);
  25.            if ((Interfaz_red == null) || (Interfaz_red.Length < 1))
  26.            {
  27.                Console.WriteLine("  No hay interfaces de red encontrados.");
  28.                return;
  29.            }
  30.  
  31.            Console.WriteLine("  Número de interfaces .................... : {0}", Interfaz_red.Length);
  32.            foreach (NetworkInterface Adaptador in Interfaz_red)
  33.            {
  34.                IPInterfaceProperties Propiedades = Adaptador.GetIPProperties(); //  .GetIPInterfaceProperties();
  35.                Console.WriteLine();
  36.                Console.WriteLine(Adaptador.Description);
  37.                Console.WriteLine(String.Empty.PadLeft(Adaptador.Description.Length, '='));
  38.                Console.WriteLine("  Tipo interfaz ........................... : {0}", Adaptador.NetworkInterfaceType);
  39.                Console.Write("  Dirección física ........................ : ");
  40.                PhysicalAddress Direccion = Adaptador.GetPhysicalAddress();
  41.                byte[] bytes = Direccion.GetAddressBytes();
  42.                for (int i = 0; i < bytes.Length; i++)
  43.                {
  44.                    // Muestra la dirección física en hexadecimal.
  45.                    Console.Write("{0}", bytes[i].ToString("X2"));
  46.                    // Inserte un guión después de cada bocado, a menos que estemos al final de la dirección.
  47.                    if (i != bytes.Length - 1)
  48.                    {
  49.                        Console.Write("-");
  50.                    }
  51.                }
  52.                Console.WriteLine();
  53.            }
  54.  
  55.            // Guarda el nombre del hostname en la variable Nombre_HostName.
  56.            Nombre_HostName = Propiedades_PC.HostName;
  57.  
  58.            // Guarda el nombre del dominio si lo tiene.
  59.            Nombre_Dominio = Propiedades_PC.DomainName;
  60.  
  61.  
  62.            // Guarda la MAC recibida con sus - en la varible MAC.
  63.            MAC = Encoding.UTF8.GetString(bytes);
  64.  
  65.            Console.WriteLine();
  66.            Console.WriteLine(@"Nombre del HostName: {0}", Nombre_HostName);
  67.            Console.WriteLine(@"Nombre del domninio: {0}", Nombre_Dominio);
  68.            Console.WriteLine(@"MAC es: {0}", MAC);
  69.            Console.ReadKey(); // Pulsa cualquier tecla y sale.
  70.        }
  71.    }
  72. }
  73.  

Citar
Gravedad   Código   Descripción   Proyecto   Archivo   Línea
Error   CS0103   El nombre 'bytes' no existe en el contexto actual   Leer_MAC   C:\Users\Usuario\Documents\Visual Studio 2015\Projects\Leer_MAC\Leer_MAC\Program.cs   65

Buscando el cambio de tipo de Byte[] a string no me ha funcionado. En esta web ayuda como se hace.
http://www.convertdatatypes.com/Convert-Byte-Array-to-string-in-CSharp.html

¿Alguna idea?

Saludos.


En línea

ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: Guardar la MAC en una variable.
« Respuesta #1 en: 23 Enero 2016, 17:33 pm »

Estás utilizando la variable bytes fuera del bucle. Está declarada dentro del contexto del bucle foreach.


En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Guardar la MAC en una variable.
« Respuesta #2 en: 23 Enero 2016, 17:57 pm »

Hola:

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. using System.Net.NetworkInformation; // No olvidar.
  8.  
  9. namespace Leer_MAC
  10. {
  11.    class Program
  12.    {
  13.        static void Main(string[] args)
  14.        {
  15.            Console.Title = "En busca del MAC";
  16.  
  17.            string Nombre_HostName = null;
  18.            string Nombre_Dominio = null;
  19.            string MAC = null;
  20.  
  21.            IPGlobalProperties Propiedades_PC = IPGlobalProperties.GetIPGlobalProperties();
  22.            NetworkInterface[] Interfaz_red = NetworkInterface.GetAllNetworkInterfaces();
  23.            Console.WriteLine("Información de interfaz para {0}.{1}     ",
  24.                    Propiedades_PC.HostName, Propiedades_PC.DomainName);
  25.            if ((Interfaz_red == null) || (Interfaz_red.Length < 1))
  26.            {
  27.                Console.WriteLine("  No hay interfaces de red encontrados.");
  28.                return;
  29.            }
  30.  
  31.            Console.WriteLine("  Número de interfaces .................... : {0}", Interfaz_red.Length);
  32.            foreach (NetworkInterface Adaptador in Interfaz_red)
  33.            {
  34.                IPInterfaceProperties Propiedades = Adaptador.GetIPProperties(); //  .GetIPInterfaceProperties();
  35.                Console.WriteLine();
  36.                Console.WriteLine(Adaptador.Description);
  37.                Console.WriteLine(String.Empty.PadLeft(Adaptador.Description.Length, '='));
  38.                Console.WriteLine("  Tipo interfaz ........................... : {0}", Adaptador.NetworkInterfaceType);
  39.                Console.Write("  Dirección física ........................ : ");
  40.                PhysicalAddress Direccion = Adaptador.GetPhysicalAddress();
  41.                byte[] bytes = Direccion.GetAddressBytes();
  42.                // Variable que tendra la dirección visible
  43.                string direccion_MAC = string.Empty;
  44.                // Recorrer todos los bytes de la dirección.
  45.                for (int i = 0; i < bytes.Length; i++)
  46.                {
  47.                    // Muestra la dirección física en hexadecimal.
  48.                    direccion_MAC += bytes[i].ToString("X2");
  49.                    Console.Write("{0}", bytes[i].ToString("X2"));
  50.                    // Inserte un guión después de cada bocado, a menos que estemos al final de la dirección.
  51.                    if (i != bytes.Length - 1)
  52.                    {
  53.                        // Agregar un separador, por formato.
  54.                        direccion_MAC += "-";
  55.                        Console.Write("-");
  56.                    }
  57.                    MAC = direccion_MAC;
  58.                }
  59.                Console.WriteLine();
  60.            }
  61.  
  62.            // Guarda el nombre del hostname en la variable Nombre_HostName.
  63.            Nombre_HostName = Propiedades_PC.HostName;
  64.  
  65.            // Guarda el nombre del dominio si lo tiene.
  66.            Nombre_Dominio = Propiedades_PC.DomainName;
  67.  
  68.  
  69.            // Guarda la MAC recibida con sus - en la varible MAC.
  70.            //MAC = direccion_MAC;
  71.  
  72.            Console.WriteLine();
  73.            Console.WriteLine(@"Nombre del HostName: {0}", Nombre_HostName);
  74.            Console.WriteLine(@"Nombre del domninio: {0}", Nombre_Dominio);
  75.            Console.WriteLine(@"MAC es: {0}", MAC);
  76.            Console.ReadKey(); // Pulsa cualquier tecla y sale.
  77.        }
  78.    }
  79. }

¿Hay alguna forma de tener ese MAC y guardarla en una variable general tipo string?

Me detecta todos los MAC tanto físico y virtuales. Solo me interesa el físico. Eso si, he logrado sacar la MAC pero solo me muestra el último llamado Tunnel.

Mira que llevo tiempo con esto y no me sale ni aquí ni pekín.

Saludos.
« Última modificación: 23 Enero 2016, 18:04 pm por Meta » En línea

crack81

Desconectado Desconectado

Mensajes: 222



Ver Perfil
Re: Guardar la MAC en una variable.
« Respuesta #3 en: 23 Enero 2016, 20:51 pm »

Hola no se muy bien cual es tu  falla pero mira este codigo
para optimizar un poco y ver mas facil lo que andas buscado

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.NetworkInformation; // No olvidar.
  7.  
  8. namespace Leer_MAC
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. Console.Title = "En busca del MAC";
  15.  
  16. var macAddr =
  17. (
  18. from nic in NetworkInterface.GetAllNetworkInterfaces()
  19. select nic.GetPhysicalAddress().ToString()
  20. ).ToArray();
  21.  
  22. Console.WriteLine("numero de direcciones "+macAddr.Count());
  23.  
  24. foreach(var address in macAddr){
  25. Console.WriteLine(address);
  26. }
  27.  
  28. Console.ReadLine();
  29.  
  30. }
  31. }
  32. }
En línea

Si C/C++ es el padre de los lenguajes entonces ASM es dios.
kondrag_X1

Desconectado Desconectado

Mensajes: 157


Ver Perfil
Re: Guardar la MAC en una variable.
« Respuesta #4 en: 25 Enero 2016, 21:49 pm »

Hola Crack81,

Esto es link??? Que hace falta para incluirlo alguna libreria;
Código
  1. var macAddr =
  2. (
  3. from nic in NetworkInterface.GetAllNetworkInterfaces()
  4. select nic.GetPhysicalAddress().ToString()
  5. ).ToArray();
  6.  
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Guardar la MAC en una variable.
« Respuesta #5 en: 4 Febrero 2016, 16:38 pm »

Hola no se muy bien cual es tu  falla pero mira este codigo
para optimizar un poco y ver mas facil lo que andas buscado

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.NetworkInformation; // No olvidar.
  7.  
  8. namespace Leer_MAC
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. Console.Title = "En busca del MAC";
  15.  
  16. var macAddr =
  17. (
  18. from nic in NetworkInterface.GetAllNetworkInterfaces()
  19. select nic.GetPhysicalAddress().ToString()
  20. ).ToArray();
  21.  
  22. Console.WriteLine("numero de direcciones "+macAddr.Count());
  23.  
  24. foreach(var address in macAddr){
  25. Console.WriteLine(address);
  26. }
  27.  
  28. Console.ReadLine();
  29.  
  30. }
  31. }
  32. }

Tu resultado es este. Buen trabajo todo simplificado.


Muy bueno que lo has hecho simple.
Por lo que se ve, el primer MAC que detecta es el físico. De alguna manera quiero guardar en una variable el primer MAC, que es el físico que se está usando en mi caso de mi ordenador. Lo puse marcado en rojo porque no quiero ponerlo en público.

Si son todas las MAC, pues todas. Lo que quiero hacer es guardar en un archivo binario dicha más en un archivo.txt, también lo podemos llamar archivo.bin para hacer más exacto.

Primer ejemplo archivo de texto y binario. Me da error.
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. using System.Net.NetworkInformation; // No olvidar.
  8. using System.IO;
  9.  
  10. namespace Leer_MAC_2
  11. {
  12.    class Program
  13.    {
  14.        static void Main(string[] args)
  15.        {
  16.            Console.Title = "Leer MAC 2";
  17.            var macAddr =
  18.    (
  19.        from nic in NetworkInterface.GetAllNetworkInterfaces()
  20.        select nic.GetPhysicalAddress().ToString()
  21.    ).ToArray();
  22.  
  23.            // Para escribir datos en un archivo.
  24.            StreamWriter Texto = new StreamWriter("Archivo.txt");
  25.            Console.WriteLine("numero de direcciones " + macAddr.Count());
  26.  
  27.            foreach (var address in macAddr)
  28.            {
  29.                Texto.Write(address);
  30.                Console.WriteLine(address);
  31.            }
  32.  
  33.            Texto.Close(); // Cerrar archivo.
  34.  
  35.            FileStream Archivo = new FileStream("Archivo.txt", FileMode.Append);
  36.            BinaryWriter Binario = new BinaryWriter(Archivo); // Escribe en bibario.
  37.            Binario.Write(macAddr); // Error aquí.
  38.            Archivo.Close(); // Cierra archivo binario.
  39.            Console.ReadKey(); // Pulse cualquier tecla para salir.
  40.        }
  41.    }
  42. }
  43.  

Mi idea es guardar la MAC o todas las MAC obtenidas en un archivo de texto o binario. En este ejemplo hace de las dos cosas para que podamos ver los ejemplos.

A lo mejor es prferible usar primero solo archivo de texto plano para ver si se puede guardar bien los datos. Luego con otro ejemplo se guarda en binario para que nadie sepa que hay dentro de ese archivo, por ejemplo, su MAC.

Le envío este programa y crea un archivo, en el cual pediré por e-mail el archivo.txt o el archivo.bin para luego leerlo en mi casa con otro programa.

Antes, debo acabar bien este programa.
Me dice este error.
Citar
Gravedad   Código   Descripción   Proyecto   Archivo   Línea
Error   CS1503   Argumento 1: no se puede convertir de 'string[]' a 'bool'   Leer_MAC_2   c:\users\usuario\documents\visual studio 2015\Projects\Leer_MAC_2\Leer_MAC_2\Program.cs   37

Sin usar el archivo binario, me muestra estos valores.
Citar
XXXXXXXXXXXX0A002700000000000000000000E000000000000000E000000000000000E0

Donde la XXXXXXXXXXXX es mi MAC en este caso. Los demás son otros MAC virtuales.

Sólo falta hacer lo mismo en binario.

Saludos.
« Última modificación: 4 Febrero 2016, 16:50 pm por Meta » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Guardar en bat! (creando variable...)
Scripting
arcanset 3 5,834 Último mensaje 20 Octubre 2008, 18:26 pm
por arcanset
Guardar valor textbox en variable
Java
Debci 3 23,919 Último mensaje 17 Marzo 2009, 18:31 pm
por Debci
Guardar contenido de variable en un TXT
Java
Blitzkrieg' 5 8,389 Último mensaje 18 Septiembre 2009, 16:29 pm
por Amerikano|Cls
guardar resultado SQL en variable
Programación Visual Basic
carnero 7 19,504 Último mensaje 11 Noviembre 2009, 03:22 am
por cassiani
Guardar en una variable el resultado de una reg query en cmd
Programación Visual Basic
Davishh 2 4,664 Último mensaje 16 Enero 2013, 21:01 pm
por Davishh
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines