我正在运行一个服务器,我想显示我自己的IP地址。

获取计算机自身(如果可能的话,外部)IP地址的语法是什么?

有人编写了以下代码。

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

然而,我通常不信任作者,我不理解这段代码。有更好的方法吗?


当前回答

using System;
using System.Net;

namespace IPADDRESS
{
    class Program
    {
        static void Main(string[] args)
        {
            String strHostName = string.Empty;
            if (args.Length == 0)
            {                
                /* 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());
            }
            Console.ReadLine();
        }
    }
}

其他回答

return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

简单的一行代码,返回第一个内部IPV4地址,如果没有则返回null。作为上面的注释添加,但可能对某人有用(上面的一些解决方案将返回多个需要进一步过滤的地址)。

它也很容易返回环回而不是null,我猜用:

return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) ?? new IPAddress( new byte[] {127, 0, 0, 1} );

如果你不能依赖于从DNS服务器获取你的IP地址(这发生在我身上),你可以使用以下方法:

System.Net.NetworkInformation命名空间包含一个NetworkInterface类,该类有一个静态的GetAllNetworkInterfaces方法。

此方法将返回您机器上的所有“网络接口”,而且通常有相当多的“网络接口”,即使您的机器上只安装了无线适配器和/或以太网适配器硬件。所有这些网络接口都有本地计算机的有效IP地址,尽管您可能只需要一个。

如果您正在寻找一个IP地址,那么您将需要筛选列表,直到您可以识别正确的地址。你可能需要做一些实验,但我成功地采用了以下方法:

通过检查OperationalStatus == OperationalStatus. up过滤掉任何非活动的网络接口。这将排除您的物理以太网适配器,例如,如果您没有插入网线。

对于每个NetworkInterface,你可以使用GetIPProperties方法获得一个IPInterfaceProperties对象,并且从一个IPInterfaceProperties对象中,你可以访问UnicastIPAddressInformation对象列表的UnicastAddresses属性。

通过检查DuplicateAddressDetectionState == DuplicateAddressDetectionState过滤掉非首选单播地址。首选 通过检查AddressPreferredLifetime != UInt32.MaxValue过滤出“虚拟”地址。

此时,我取与所有这些过滤器匹配的第一个单播地址(如果有的话)的地址。

编辑:

[2018年5月16日修订的代码,以包括上述文本中提到的重复地址检测状态和首选生存期的条件]

下面的示例演示了基于操作状态、地址族、排除环回地址(127.0.0.1)、重复地址检测状态和首选生存期的过滤。

static IEnumerable<IPAddress> GetLocalIpAddresses()
{
    // Get the list of network interfaces for the local computer.
    var adapters = NetworkInterface.GetAllNetworkInterfaces();

    // Return the list of local IPv4 addresses excluding the local
    // host, disconnected, and virtual addresses.
    return (from adapter in adapters
            let properties = adapter.GetIPProperties()
            from address in properties.UnicastAddresses
            where adapter.OperationalStatus == OperationalStatus.Up &&
                  address.Address.AddressFamily == AddressFamily.InterNetwork &&
                  !address.Equals(IPAddress.Loopback) &&
                  address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
                  address.AddressPreferredLifetime != UInt32.MaxValue
            select address.Address);
}

这是我解决它的方法。我知道如果你有几个物理接口,这可能不会选择你想要的确切的eth。

private string FetchIP()
{
    //Get all IP registered
    List<string> IPList = new List<string>();
    IPHostEntry host;
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            IPList.Add(ip.ToString());
        }
    }

    //Find the first IP which is not only local
    foreach (string a in IPList)
    {
        Ping p = new Ping();
        string[] b = a.Split('.');
        string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
        PingReply t = p.Send(ip2);
        p.Dispose();
        if (t.Status == IPStatus.Success && ip2 != a)
        {
            return a;
        }
    }
    return null;
}

这个问题没有说ASP。NET MVC,但我还是把这个留在这里:

Request.UserHostAddress
namespace NKUtilities 
{
    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;
        }    
     }
}