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

问题描述 投票:17回答:6

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

我习惯使用Request.ServerVariables集合和/或Request.UserHostAddress进行Web应用程序。

如何在控制台应用程序中完成?

c# console-application
6个回答
27
投票

最简单的方法如下:

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

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等),因此问题并不像您提出的那么简单。


2
投票

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


1
投票

System.Net.Dns.GetHostAddresses()应该这样做。


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

© www.soinside.com 2019 - 2024. All rights reserved.