Domanda

Sto cercando di capire che cosa il mio indirizzo IP è da un'applicazione console.

Sono abituato a un'applicazione web utilizzando il Request.ServerVariables raccolta e / o Request.UserHostAddress.

Come può essere fatto in una console app?

È stato utile?

Soluzione

Il modo più semplice per farlo è la seguente:

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

Altri suggerimenti

Prova questo:

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

Lo spazio dei nomi System.Net è tuo amico qui. In particolare, API come DNS.GetHostByName.

Tuttavia, qualsiasi data macchina può avere più indirizzi IP (più schede NIC, IPv4 e IPv6, ecc) in modo che non è così semplice una domanda come si pongono.

IPAddress [] = addresslist Dns.GetHostAddresses (Dns.GetHostName ());

System.Net.Dns.GetHostAddresses () dovrebbe farlo.

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top