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

В этой ошибке вы используете итерацию в объекте ... В ионной итерации выполняется только массив

17
задан p.campbell 2 February 2015 в 16:18
поделиться

6 ответов

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

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();
        }
    }
}
27
ответ дан 30 November 2019 в 11:52
поделиться
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/KB/cs/network.aspx

1
ответ дан 30 November 2019 в 11:52
поделиться

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

1
ответ дан 30 November 2019 в 11:52
поделиться

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

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

2
ответ дан 30 November 2019 в 11:52
поделиться

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

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
ответ дан 30 November 2019 в 11:52
поделиться

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

2
ответ дан 30 November 2019 в 11:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: