2010-11-10 37 views

Respuesta

0

Este artículo no es una descripción técnica general o una gran discusión. Es como una colección de consejos sobre cómo puede obtener la dirección IP o el nombre de host de una máquina. En la API de Win32 esto podría lograrse utilizando la API de NetWork. Y esto sigue siendo cierto en el marco .NET. La única diferencia es encontrar y comprender qué espacio de nombres y clase usar para lograr esta tarea. En el marco de .NET, la API de NetWork está disponible en el espacio de nombres de System.Net. La clase DNS en el espacio de nombres System.Net se puede usar para obtener el nombre de host de una máquina u obtener la dirección IP si el nombre de host ya se conoce. La clase DNS proporciona una funcionalidad simple de resolución de nombres de dominio. La clase DNS es una clase estática que proporciona acceso a la información del Sistema de nombres de dominio de Internet (DNS). La información devuelta incluye múltiples direcciones IP y alias si el host especificado tiene más de una entrada en la base de datos DNS. La lista se devuelve como una colección o una matriz de objetos IPAddress. La siguiente sección es el código que muestra cómo obtener la dirección IP para un nombre de host determinado.

namespace NKUtilities 
{ 
    using System; 
    using System.Net; 

    public class DNSUtility 
    { 
     public static int Main (string [] args) 
     { 

      String strHostName = new String (""); 
      if (args.Length == 0) 
      { 
       // Getting Ip address of local machine... 
       // First get the host name of local machine. 
       strHostName = DNS.GetHostName(); 
       Console.WriteLine ("Local Machine's Host Name: " + strHostName); 
      } 
      else 
      { 
       strHostName = args[0]; 
      } 

      // Then using host name, get the IP address list.. 
      IPHostEntry ipEntry = DNS.GetHostByName (strHostName); 
      IPAddress [] addr = ipEntry.AddressList; 

      for (int i = 0; i < addr.Length; i++) 
      { 
       Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString()); 
      } 
      return 0; 
     }  
    } 
} 

http://www.codeproject.com/Articles/854/How-To-Get-IP-Address-Of-A-Machine

+0

ese enlace parece estar muerto. – Sevki

+0

El enlace anterior se refiere a obtener la dirección IP. Necesito la dirección MAC y no la dirección IP. – Vicky

0
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 
//for each j you can get the MAC 
PhysicalAddress address = nics[0].GetPhysicalAddress(); 
byte[] bytes = address.GetAddressBytes(); 
for (int i = 0; i < bytes.Length; i++) 
{ 
    // Display the physical address in hexadecimal. 
    Console.Write("{0}", bytes[i].ToString("X2")); 
    // Insert a hyphen after each byte, unless we are at the end of the 
    // address. 
    if (i != bytes.Length - 1) 
    { 
     Console.Write("-"); 
    } 
} 
+1

De acuerdo con los documentos, NetworkInterface y PhysicalAddress son compatibles con el marco compacto. – c0D3l0g1c

+1

Según esto: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface_members(v=VS.90).aspx, veo que no es compatible con el marco compacto. No estoy seguro a qué documentos se refiere. – Vicky

0

Podemos utilizar MDSDK en este tipo de problemas como

using PsionTeklogix.Peripherals; 
namespace EnumAdapters 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 

      ArrayList pList = null; 
      string[] lStatistic = null; 

      try 
      { 
       pList = Peripherals.EnumerateAdapters(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("failed with\r\n" + ex.Message, "EnumerateAdapters()"); 
       Close(); 
       return; 
      } 

      listBox1.Items.Clear(); 

      foreach (string AdapterName in pList) 
      { 
       try 
       { 
        listBox1.Items.Add(AdapterName + (Peripherals.IsAdapterPresent(AdapterName) ? " is present" : " is NOT present") + (Peripherals.IsWirelessAdapter(AdapterName) ? " [wireless adapter] " : "")); 
        lStatistic = Peripherals.GetAdapterStatistics(AdapterName); // See Note 1 
        foreach (string StatInfo in lStatistic) 
        { 
         if (StatInfo.StartsWith("Local MAC Address")) 
         { 
          listBox1.Items.Add("» " + StatInfo); 
          break; 
         } 
        } 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.Message); 
        Close(); 
        return; 
       } 
      } 
     } 
    } 
} 
+1

Esto usa una biblioteca específica del dispositivo y por lo tanto funcionará * solo * con el dispositivo Psion. – ctacke

3

Sé que ha sido un tiempo, pero necesitaba esto y encontró que podía usar OpenNETCF versión del código anterior con un tweak:

INetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 
//for each j you can get the MAC 
PhysicalAddress address = nics[0].GetPhysicalAddress(); 
byte[] bytes = address.GetAddressBytes(); 
for(int i = 0; i < bytes.Length; i++) { 
    // Display the physical address in hexadecimal. 
    Console.Write("{0}", bytes[i].ToString("X2")); 
    // Insert a hyphen after each byte, unless we are at the end of the address. 
    if(i != bytes.Length - 1) { 
     Console.Write("-"); 
    } 
} 
Cuestiones relacionadas