Подтвердить что ты не робот

Получить IP-адрес в консольном приложении

Я ищу, чтобы выяснить, что мой IP-адрес из консольного приложения.

Я использую веб-приложение с помощью коллекции Request.ServerVariables и/или Request.UserHostAddress.

Как это можно сделать в консольном приложении?

4b9b3361

Ответ 1

Самый простой способ сделать это:

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

Ответ 2

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

Ответ 3

Пространство имен System.Net - ваш друг здесь. В частности, API, такие как DNS.GetHostByName.

Однако любой компьютер может иметь несколько IP-адресов (несколько сетевых адаптеров, IPv4 и IPv6 и т.д.), поэтому он не так прост, как вы представляете.

Ответ 4

Попробуйте следующее:

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

Ответ 5

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 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/KB/cs/network.aspx

Ответ 6

System.Net.Dns.GetHostAddresses() должен это сделать.