2009-05-13 16 views
16

Estoy buscando averiguar cuál es mi dirección IP desde una aplicación de consola.Obtener la dirección IP en una aplicación de consola

Estoy acostumbrado a una aplicación web utilizando la colección Request.ServerVariables y/o Request.UserHostAddress.

¿Cómo se puede hacer esto en una aplicación de consola?

Respuesta

23

La forma más sencilla de hacerlo es la siguiente:

using System; 
using System.Net; 


namespace ConsoleTest 
{ 
    class Program 
    { 
     static void Main() 
     { 
      String strHostName = string.Empty; 
      // 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); 
      // Then using host name, get the IP address list.. 
      IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); 
      IPAddress[] addr = ipEntry.AddressList; 

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

Bien, entonces veo muchas respuestas aquí, pero parece fácil de leer. Me gusta lo que Martin Peck dijo acerca de tener múltiples direcciones IP, y creo que esto aquí me da la solución correcta. Ejecuté esto localmente y me dio lo que quería. Muchas gracias! –

+1

Sí, estoy de acuerdo con Martin, debes tener en cuenta las múltiples direcciones IP. Este código manejará esto y puede elegir qué hacer desde allí. – CodeLikeBeaker

+2

Probablemente deberías incluir un enlace a la página desde la que copiaste este código, ¿no crees? Quiero decir, es uno de los primeros resultados en Google. – Kevin

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

fuente: http://www.codeproject.com/KB/cs/network.aspx

1

System.Net.Dns.GetHostAddresses() deben hacerlo.

2

El espacio de nombres de System.Net es tu amigo aquí. En particular, API como DNS.GetHostByName.

Sin embargo, cualquier máquina puede tener múltiples direcciones IP (múltiples NIC, IPv4 e IPv6, etc.) por lo que no es una pregunta tan simple como la que plantea.

+0

Me gusta mucho tu comentario por tener varias direcciones IP. Basado en que el código anterior funcionó muy bien. ¡Gracias! –

2

Prueba esto:

String strHostName = Dns.GetHostName(); 

Console.WriteLine("Host Name: " + strHostName); 

// Find host by name IPHostEntry 
iphostentry = Dns.GetHostByName(strHostName); 

// Enumerate IP addresses 
int nIP = 0; 
foreach(IPAddress ipaddress in iphostentry.AddressList) { 
    Console.WriteLine("IP #" + ++nIP + ": " + ipaddress.ToString());  
} 
3

Dirección IP [] AddressList = Dns.GetHostAddresses (Dns.GetHostName());

Cuestiones relacionadas