在控制台应用程序中获取IP地址

19

我想从控制台应用程序中找出我的IP地址。

我通常使用Request.ServerVariables集合和/或 Request.UserHostAddress在Web应用程序中获取IP地址。

在控制台应用程序中,如何完成这项任务呢?

6个回答

31

最简单的方法是按照以下步骤进行:

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

好的,我看到很多答案,但这个似乎很容易阅读。我喜欢Martin Peck关于拥有多个IP地址的说法,我认为这里给了我正确的解决方案。我在本地运行了它,它给了我想要的结果。非常感谢! - Computer Girl
1
是的,我同意马丁的观点,你必须注意多个IP地址。这段代码将处理此问题,然后您可以选择如何处理它。 - CodeLikeBeaker
3
你或许应该包含一个链接,指向你复制这段代码的页面,不是吗?我的意思是,这个页面在谷歌上是最早的几个搜索结果之一。 - Kevin
你说得完全正确。我之前恰好使用过这个代码块并从那里复制了它,但我最初获取它的资源在这里:http://www.codeproject.com/KB/cs/network.aspx - CodeLikeBeaker
为什么所有这些答案都使用 strHostName 的匈牙利命名法,但没有其他变量呢? - Richard Szalay

3

试试这个:

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

2

System.Net命名空间是您的好帮手。特别是像DNS.GetHostByName这样的API。

然而,任何一台计算机可能有多个IP地址(多个NIC、IPv4和IPv6等),所以这并不像您提出的问题那么简单。


我非常喜欢你的评论,提到了具有多个IP地址。基于此,上面的代码确实运行良好。谢谢! - Computer Girl

2

使用Dns.GetHostName()获得主机名,然后使用Dns.GetHostAddresses()获取IPAddress数组。


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

来源:http://www.codeproject.com/KB/cs/network.aspx


1

应该使用System.Net.Dns.GetHostAddresses()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接