【问题标题】:How to get the IP address of the server on which my C# application is running on?如何获取运行我的 C# 应用程序的服务器的 IP 地址?
【发布时间】:2010-11-07 08:00:33
【问题描述】:

我正在运行一个服务器,我想显示我自己的 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;

但是,我一般不信任作者,也看不懂这段代码。有更好的方法吗?

【问题讨论】:

  • 关于外部 IP 地址,我认为没有本地方法可以检索它。本地主机可能位于将本地网络地址转换为公共地址的 NAT 路由器后面。是否有(本地)方法来验证是否是这种情况?我不知道任何...
  • 本示例使用 DNS 获取 IP 地址,我曾遇到过 DNS 信息错误的情况。在这种情况下,样本可能会以错误信息进行响应。
  • @leiflundgren 我也有过 DNS 信息错误的经验。我的回答描述了我在遇到这种情况时如何在不依赖 DNS 的情况下获得所需的 IP 地址。
  • 使用 LINQ:Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First().ToString()
  • 这是一个典型的情况,有完全不同需求的用户往往会问同样的问题。有些人想知道如何从公共网络访问他们的计算机。规范的答案是STUN,尽管许多答案都是依赖于随机第三方的黑客攻击。有些人只想知道他们在本地网络上的 IP 地址。在这种情况下,好的答案提到NetworkInterface.GetAllNetworkInterfaces Method

标签: c# ip-address


【解决方案1】:

不,这几乎是最好的方法。作为一台机器可能有多个 IP 地址,您需要迭代它们的集合以找到合适的。

编辑:唯一改变的就是改变这个:

if (ip.AddressFamily.ToString() == "InterNetwork")

到这里:

if (ip.AddressFamily == AddressFamily.InterNetwork)

无需ToString 枚举进行比较。

【讨论】:

  • 如果可能的话,我想要外部 IP 地址。如果我在 NAT 之后,我想这不可能。
  • 不,你的机器只会知道它的 NAT 地址。
  • 我很确定您需要访问外部服务器以获取外部地址。
  • 我还建议在找到 IP 后使用break 声明,以避免不必要地进一步遍历集合(在这种情况下,我怀疑性能影响是否会很重要,但我想强调一下良好的编码习惯)
  • 请注意,当机器有多个“InterNetwork”端口(在我的情况下:以太网卡和虚拟机端口)时,这可能会失败。当前代码将为您提供列表中的最后一个 IP。
【解决方案2】:

知道你的公共 IP 的唯一方法是请别人告诉你;此代码可能会对您有所帮助:

public string GetPublicIP()
{
    String direction = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
    {
        direction = stream.ReadToEnd();
    }

    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);

    return direction;
}

【讨论】:

  • 您知道您的代码示例在 Microsoft Academy 的问题 13 解释的 20 个 C# 问题中被提及吗?演示者为窃取您的代码而道歉。从 8 点 30 分开始。见this。 :)
  • 不幸的是链接失效了。
  • New link 以防有人想看
  • 请使用链接ipof.in/txt,这样您就可以直接获得IP a,无需所有HTML解析代码
【解决方案3】:

清洁剂和多合一解决方案:D

//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

【讨论】:

  • 此代码的问题: * 它假定计算机只有一个 IP 地址。许多有多个。 * 它只考虑 IPV4 地址。添加 InterNetworkV6 以包含 IPV6。
  • @RobertBratton,感谢您的重播。该问题并非假设是多 IP 地址或 IPV6,只要稍加修改此代码即可处理特定的不同问题。
【解决方案4】:

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

System.Net.NetworkInformation 命名空间包含一个NetworkInterface class,其中有一个静态GetAllNetworkInterfaces method

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

如果您正在寻找一个 IP 地址,则需要向下过滤列表,直到您可以识别出正确的地址。您可能需要做一些实验,但我通过以下方法取得了成功:

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

对于每个 NetworkInterface,您可以使用 GetIPProperties method 获取一个 IPInterfaceProperties 对象,并且您可以从 IPInterfaceProperties 对象访问 UnicastAddresses property 以获取 UnicastIPAddressInformation 对象的列表。

  • 通过检查DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred 过滤掉非首选的单播地址
  • 通过检查 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);
}

【讨论】:

  • 在这种特殊情况下,OP 想要查看他的外部 IP 地址,因此 DNS 解决方案可能是要走的路。但是对于迭代本地 IP 地址,这是我推荐的方法。
  • 同意 DNS 是一种更简单的获取 IP 地址的方法。我在回答中提到,当您的 DNS 不可靠时,这种方法有效。我在 DNS 混乱的环境中使用了这个,如果你将一台机器从一个以太网端口移动到另一个,DNS 仍然会报告旧的 IP 地址,所以它对我的目的几乎没有用。
  • 感谢所有描述,但您也应该发布代码示例。
  • 非常感谢。请注意,在最近的 Windows 更新之后,UnicastAddresses. 第一个假设不再成立。我现在需要检查每个适配器的 all UnicastAddress,并使用 AddressPreferredLifetimeDuplicateAddressDetectionStation (在上面的文本中提到)
【解决方案5】:
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");

【讨论】:

  • ifconfig.me/ip 不再有效。试试api.ipify.org 或 Doug 评论中的链接
【解决方案6】:
using System.Net;

string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());

刚刚在我的机器上测试过,它可以工作。

【讨论】:

  • 它会得到你的本地IP,问题是关于外部IP,即你浏览互联网的IP..
【解决方案7】:

如果您想避免使用 DNS:

List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
    {
        if (address.Address.AddressFamily == AddressFamily.InterNetwork)
        {
            Console.WriteLine("found IP " + address.Address.ToString());
            ipList.Add(address.Address);
        }
    }
}

【讨论】:

    【解决方案8】:

    不要一直依赖 InterNetwork,因为您可以拥有多个设备,这些设备也使用 IP4,这会破坏获取 IP 的结果。 现在,如果您愿意,您可以直接复制此内容,然后查看或更新到您认为合适的位置。

    首先我得到路由器(网关)的地址 如果返回我已连接到网关(这意味着未直接连接到无线调制解调器),那么我们将网关地址作为 IPAddress,否则我们将使用空指针 IPAddress 引用。

    然后我们需要获取计算机的 IPAddresses 列表。这就是事情不那么难的地方,因为路由器(所有路由器)使用 4 个字节(...)。前三个是最重要的,因为任何连接到它的计算机都将具有与前三个字节匹配的 IP4 地址。例如:除非管理员更改,否则 192.168.0.1 是路由器默认 IP 的标准。 '192.168.0' 或任何它们可能是我们需要匹配的。这就是我在 IsAddressOfGateway 函数中所做的一切。 长度匹配的原因是因为并非所有地址(仅适用于计算机)都具有 4 个字节的长度。如果你在 cmd 中输入 netstat,你会发现这是真的。所以你有它。是的,要真正得到你想要的东西需要更多的工作。排除法。 看在上帝的份上,不要通过 ping 地址找到地址,这需要时间,因为首先您要发送要 ping 的地址,然后它必须将结果发回。不,直接使用处理您的系统环境的 .Net 类,当它只与您的计算机有关时,您会得到您正在寻找的答案。

    现在,如果您直接连接到调制解调器,该过程几乎相同,因为调制解调器是您的网关,但子掩码不一样,因为您通过调制解调器直接从 DNS 服务器获取信息,而不是被路由器屏蔽尽管您仍然可以使用相同的代码为您提供 Internet,因为分配给调制解调器的 IP 的最后一个字节是 1。因此,如果从确实发生变化的调制解调器发送的 IP 是 111.111.111.1',那么您将得到 111.111.111 .(一些字节值)。请记住,我们需要找到网关信息,因为处理互联网连接的设备比您的路由器和调制解调器要多。

    现在您明白为什么不更改路由器的前两个字节 192 和 168。这些是严格区分的,仅供路由器使用,不能用于互联网,否则我们会遇到严重的 IP 协议问题和双重 ping,导致您的计算机崩溃.假设您分配的路由器 IP 是 192.168.44.103,并且您也单击了具有该 IP 的站点。我的天啊!您的计算机将不知道要 ping 什么。就在那儿撞车。为了避免这个问题,只分配了路由器而不是用于互联网。所以不要管路由器的前两个字节。

    static IPAddress FindLanAddress()
    {
        IPAddress gateway = FindGetGatewayAddress();
        if (gateway == null)
            return null;
    
        IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());
    
        foreach (IPAddress address in pIPAddress)            {
            if (IsAddressOfGateway(address, gateway))
                    return address;
        return null;
    }
    static bool IsAddressOfGateway(IPAddress address, IPAddress gateway)
    {
        if (address != null && gateway != null)
            return IsAddressOfGateway(address.GetAddressBytes(),gateway.GetAddressBytes());
        return false;
    }
    static bool IsAddressOfGateway(byte[] address, byte[] gateway)
    {
        if (address != null && gateway != null)
        {
            int gwLen = gateway.Length;
            if (gwLen > 0)
            {
                if (address.Length == gateway.Length)
                {
                    --gwLen;
                    int counter = 0;
                    for (int i = 0; i < gwLen; i++)
                    {
                        if (address[i] == gateway[i])
                            ++counter;
                    }
                    return (counter == gwLen);
                }
            }
        }
        return false;
    
    }
    static IPAddress FindGetGatewayAddress()
    {
        IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();
    
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            IPInterfaceProperties ipInfProps = ni.GetIPProperties();
            foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)
                return gi.Address;
        }
        return null;
    }
    

    【讨论】:

    • 这没有意义:foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses) return gi.Address;
    • 无法保证“任何连接到网关的计算机的 IP4 地址都与前三个字节匹配”。它取决于子网掩码,它可以包含各种位组合。此外,起始字节不必是“192.168”,如described here。此代码仅在子网掩码为 255.255.255.0 时才有效,并且 IMO 将以相当复杂的方式执行此操作。
    【解决方案9】:

    我只是想我会添加我自己的单行(即使已经有许多其他有用的答案)。


    string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

    【讨论】:

    • 请注意,这可能存在内存泄漏。 WebClient 未正确处理。相反,使用: using (var client = new WebClient()) { return client.DownloadString("icanhazip.com/").Trim(); }
    【解决方案10】:

    要获取当前的公共 IP 地址,您需要做的就是创建一个 ASPX 页面,在页面加载事件中使用以下行:

    Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
    

    【讨论】:

      【解决方案11】:

      如果您在 Intranet 中运行,您将能够获取本地计算机 IP 地址,否则您将通过以下方式获取外部 IP 地址: 网页:

      //this will bring the IP for the current machine on browser
      System.Web.HttpContext.Current.Request.UserHostAddress
      

      桌面:

      //This one will bring all local IPs for the desired namespace
      IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
      

      【讨论】:

        【解决方案12】:
        namespace NKUtilities 
        {
            using System;
            using System.Net;
            using System.Net.Sockets;
        
            public class DNSUtility
            {
                public static int Main(string [] args)
                {
                    string strHostName = "";
                    try {
        
                        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
                        {
                            // Otherwise, get the IP address of the host provided on the command line.
                            strHostName = args[0];
                        }
        
                        // 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());
                        }
                        return 0;
        
                    } 
                    catch(SocketException se) 
                    {
                        Console.WriteLine("{0} ({1})", se.Message, strHostName);
                        return -1;
                    } 
                    catch(Exception ex) 
                    {
                        Console.WriteLine("Error: {0}.", ex.Message);
                        return -1;
                    }
                }
            }
        }
        

        查看here了解详情。

        您必须记住,您的计算机可以拥有多个 IP(实际上总是如此)——那么您要的是哪一个。

        【讨论】:

          【解决方案13】:

          试试这个:

           IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
           String MyIp = localIPs[0].ToString();
          

          【讨论】:

          • 这会返回多个本地 IP 地址,其中一个是 IPv4 地址,但是很难在列表中找到正确的。
          【解决方案14】:

          也许通过外部 IP,您可以考虑(如果您在 Web 服务器环境中)使用此

          Request.ServerVariables["LOCAL_ADDR"];
          

          我和你问了同样的问题,我在thisstackoverflow 文章中找到了它。

          它对我有用。

          【讨论】:

            【解决方案15】:
            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;
                    }    
                 }
            }
            

            【讨论】:

              【解决方案16】:
              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();
                      }
                  }
              }
              

              【讨论】:

                【解决方案17】:
                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} );
                

                【讨论】:

                • IPAddress.Loopback 怎么样? :)
                【解决方案18】:

                为了查找 IP 地址列表,我使用了这个解决方案

                public static IEnumerable<string> GetAddresses()
                {
                    var host = Dns.GetHostEntry(Dns.GetHostName());
                    return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
                }
                

                但我个人喜欢以下获取本地有效 IP地址的解决方案

                public static IPAddress GetIPAddress(string hostName)
                {
                    Ping ping = new Ping();
                    var replay = ping.Send(hostName);
                
                    if (replay.Status == IPStatus.Success)
                    {
                        return replay.Address;
                    }
                    return null;
                 }
                
                public static void Main()
                {
                    Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
                    Console.WriteLine("Google IP:" + GetIPAddress("google.com");
                    Console.ReadLine();
                }
                

                【讨论】:

                  【解决方案19】:

                  LINQ 解决方案:

                  Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
                  

                  【讨论】:

                    【解决方案20】:

                    这就是我解决它的方法。我知道如果您有多个物理接口,这可能无法选择您想要的确切 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;
                    }
                    

                    【讨论】:

                      【解决方案21】:

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

                      Request.UserHostAddress
                      

                      【讨论】:

                      • 这仅在涉及请求时才有效。如果它是每隔几个小时在服务器上运行的工作人员怎么办?
                      【解决方案22】:

                      使用 LINQ 将所有 IP 地址作为字符串获取:

                      using System.Linq;
                      using System.Net.NetworkInformation;
                      using System.Net.Sockets;
                      ...
                      string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
                          .SelectMany(c=>c.GetIPProperties().UnicastAddresses
                              .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
                              .Select(d=>d.Address.ToString())
                          ).ToArray();
                      

                      过滤掉私人的......

                      首先,定义一个扩展方法IsPrivate()

                      public static class IPAddressExtensions
                      {
                          // Collection of private CIDRs (IpAddress/Mask) 
                          private static Tuple<int, int>[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
                              .Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
                                                          .Parse(c.Split('/')[0]).GetAddressBytes(), 0)
                                                    , IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
                              .ToArray();
                          public static bool IsPrivate(this IPAddress ipAddress)
                          {
                              int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
                              return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));           
                          }
                      }
                      

                      ...然后用它来过滤掉私有IP:

                      string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
                          .SelectMany(c=>c.GetIPProperties().UnicastAddresses
                              .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
                                  && !d.Address.IsPrivate() // Filter out private ones
                              )
                              .Select(d=>d.Address.ToString())
                          ).ToArray();
                      

                      【讨论】:

                        【解决方案23】:

                        它适用于我...并且在大多数情况下(如果不是全部)应该比查询 DNS 服务器更快。感谢 Wily 博士的学徒 (here)。

                        // ************************************************************************
                        /// <summary>
                        /// Will search for the an active NetworkInterafce that has a Gateway, otherwise
                        /// it will fallback to try from the DNS which is not safe.
                        /// </summary>
                        /// <returns></returns>
                        public static NetworkInterface GetMainNetworkInterface()
                        {
                            List<NetworkInterface> candidates = new List<NetworkInterface>();
                        
                            if (NetworkInterface.GetIsNetworkAvailable())
                            {
                                NetworkInterface[] NetworkInterfaces =
                                    NetworkInterface.GetAllNetworkInterfaces();
                        
                                foreach (
                                    NetworkInterface ni in NetworkInterfaces)
                                {
                                    if (ni.OperationalStatus == OperationalStatus.Up)
                                        candidates.Add(ni);
                                }
                            }
                        
                            if (candidates.Count == 1)
                            {
                                return candidates[0];
                            }
                        
                            // Accoring to our tech, the main NetworkInterface should have a Gateway 
                            // and it should be the ony one with a gateway.
                            if (candidates.Count > 1)
                            {
                                for (int n = candidates.Count - 1; n >= 0; n--)
                                {
                                    if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
                                    {
                                        candidates.RemoveAt(n);
                                    }
                                }
                        
                                if (candidates.Count == 1)
                                {
                                    return candidates[0];
                                }
                            }
                        
                            // Fallback to try by getting my ipAdress from the dns
                            IPAddress myMainIpAdress = null;
                            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                            foreach (IPAddress ip in host.AddressList)
                            {
                                if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
                                {
                                    myMainIpAdress = ip;
                                    break;
                                }
                            }
                        
                            if (myMainIpAdress != null)
                            {
                                NetworkInterface[] NetworkInterfaces =
                                    NetworkInterface.GetAllNetworkInterfaces();
                        
                                foreach (NetworkInterface ni in NetworkInterfaces)
                                {
                                    if (ni.OperationalStatus == OperationalStatus.Up)
                                    {
                                        IPInterfaceProperties props = ni.GetIPProperties();
                                        foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                                        {
                                            if (ai.Address.Equals(myMainIpAdress))
                                            {
                                                return ni;
                                            }
                                        }
                                    }
                                }
                            }
                        
                            return null;
                        }
                        
                        // ******************************************************************
                        /// <summary>
                        /// AddressFamily.InterNetwork = IPv4
                        /// Thanks to Dr. Wilys Apprentice at
                        /// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
                        /// using System.Net.NetworkInformation;
                        /// </summary>
                        /// <param name="mac"></param>
                        /// <param name="addressFamily">AddressFamily.InterNetwork = IPv4,  AddressFamily.InterNetworkV6 = IPv6</param>
                        /// <returns></returns>
                        public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
                        {
                            NetworkInterface[] NetworkInterfaces =
                                NetworkInterface.GetAllNetworkInterfaces();
                        
                            foreach (NetworkInterface ni in NetworkInterfaces)
                            {
                                if (ni.GetPhysicalAddress().Equals(mac))
                                {
                                    if (ni.OperationalStatus == OperationalStatus.Up)
                                    {
                                        IPInterfaceProperties props = ni.GetIPProperties();
                                        foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                                        {
                                            if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
                                            {
                                                if (ai.Address.AddressFamily == addressFamily)
                                                {
                                                    return ai.Address;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        
                            return null;
                        }
                        
                        // ******************************************************************
                        /// <summary>
                        /// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call 
                        /// '?.ToString() ?? ""' on the result.
                        /// </summary>
                        /// <returns></returns>
                        public static IPAddress GetMyInternetIpAddress()
                        {
                            NetworkInterface ni = GetMainNetworkInterface();
                            IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
                            if (ipAddress == null) // could it be possible ?
                            {
                                ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
                            }
                        
                            return ipAddress;
                        }
                        
                        // ******************************************************************
                        

                        作为参考,这是我定义它的完整类代码:

                        using System;
                        using System.Collections.Concurrent;
                        using System.Collections.Generic;
                        using System.Diagnostics;
                        using System.Linq;
                        using System.Net;
                        using System.Net.NetworkInformation;
                        using System.Net.Sockets;
                        using System.Runtime.InteropServices;
                        using System.Threading.Tasks;
                        
                        namespace TcpMonitor
                        {
                            /*
                                Usage:
                                        var cons = TcpHelper.GetAllTCPConnections();
                                        foreach (TcpHelper.MIB_TCPROW_OWNER_PID c in cons) ...
                            */
                        
                            public class NetHelper
                            {
                                [DllImport("iphlpapi.dll", SetLastError = true)]
                                static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int dwOutBufLen, bool sort, int ipVersion, UDP_TABLE_CLASS tblClass, uint reserved = 0);
                        
                                public enum UDP_TABLE_CLASS
                                {
                                    UDP_TABLE_BASIC,
                                    UDP_TABLE_OWNER_PID,
                                    UDP_TABLE_OWNER_MODULE
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_UDPTABLE_OWNER_PID
                                {
                                    public uint dwNumEntries;
                                    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
                                    public MIB_UDPROW_OWNER_PID[] table;
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_UDPROW_OWNER_PID
                                {
                                    public uint localAddr;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] localPort;
                                    public uint owningPid;
                        
                                    public uint ProcessId
                                    {
                                        get { return owningPid; }
                                    }
                        
                                    public IPAddress LocalAddress
                                    {
                                        get { return new IPAddress(localAddr); }
                                    }
                        
                                    public ushort LocalPort
                                    {
                                        get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
                                    }
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_UDP6TABLE_OWNER_PID
                                {
                                    public uint dwNumEntries;
                                    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
                                    public MIB_UDP6ROW_OWNER_PID[] table;
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_UDP6ROW_OWNER_PID
                                {
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
                                    public byte[] localAddr;
                                    public uint localScopeId;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] localPort;
                                    public uint owningPid;
                                    public uint ProcessId
                                    {
                                        get { return owningPid; }
                                    }
                        
                                    public IPAddress LocalAddress
                                    {
                                        get { return new IPAddress(localAddr, localScopeId); }
                                    }
                        
                                    public ushort LocalPort
                                    {
                                        get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
                                    }
                                }
                        
                                public static List<MIB_UDPROW_OWNER_PID> GetAllUDPConnections()
                                {
                                    return GetUDPConnections<MIB_UDPROW_OWNER_PID, MIB_UDPTABLE_OWNER_PID> (AF_INET);
                                }
                        
                                public static List<MIB_UDP6ROW_OWNER_PID> GetAllUDPv6Connections()
                                {
                                    return GetUDPConnections<MIB_UDP6ROW_OWNER_PID, MIB_UDP6TABLE_OWNER_PID>(AF_INET6);
                                }
                        
                                private static List<IPR> GetUDPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
                                {
                                    List<IPR> result = null;
                        
                                    IPR[] tableRows = null;
                                    int buffSize = 0;
                        
                                    var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
                        
                                    // how much memory do we need?
                                    uint ret = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                                    IntPtr udpTablePtr = Marshal.AllocHGlobal(buffSize);
                        
                                    try
                                    {
                                        ret = GetExtendedUdpTable(udpTablePtr, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
                                        if (ret != 0)
                                            return new List<IPR>();
                        
                                        // get the number of entries in the table
                                        IPT table = (IPT)Marshal.PtrToStructure(udpTablePtr, typeof(IPT));
                                        int rowStructSize = Marshal.SizeOf(typeof(IPR));
                                        uint numEntries = (uint)dwNumEntriesField.GetValue(table);
                        
                                        // buffer we will be returning
                                        tableRows = new IPR[numEntries];
                        
                                        IntPtr rowPtr = (IntPtr)((long)udpTablePtr + 4);
                                        for (int i = 0; i < numEntries; i++)
                                        {
                                            IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
                                            tableRows[i] = tcpRow;
                                            rowPtr = (IntPtr)((long)rowPtr + rowStructSize);   // next entry
                                        }
                                    }
                                    finally
                                    {
                                        result = tableRows?.ToList() ?? new List<IPR>();
                        
                                        // Free the Memory
                                        Marshal.FreeHGlobal(udpTablePtr);
                                    }
                        
                                    return result;
                                }
                        
                                [DllImport("iphlpapi.dll", SetLastError = true)]
                                static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass, uint reserved = 0);
                        
                        
                        
                                public enum MIB_TCP_STATE
                                {
                                    MIB_TCP_STATE_CLOSED = 1,
                                    MIB_TCP_STATE_LISTEN = 2,
                                    MIB_TCP_STATE_SYN_SENT = 3,
                                    MIB_TCP_STATE_SYN_RCVD = 4,
                                    MIB_TCP_STATE_ESTAB = 5,
                                    MIB_TCP_STATE_FIN_WAIT1 = 6,
                                    MIB_TCP_STATE_FIN_WAIT2 = 7,
                                    MIB_TCP_STATE_CLOSE_WAIT = 8,
                                    MIB_TCP_STATE_CLOSING = 9,
                                    MIB_TCP_STATE_LAST_ACK = 10,
                                    MIB_TCP_STATE_TIME_WAIT = 11,
                                    MIB_TCP_STATE_DELETE_TCB = 12
                                }
                        
                                public enum TCP_TABLE_CLASS
                                {
                                    TCP_TABLE_BASIC_LISTENER,
                                    TCP_TABLE_BASIC_CONNECTIONS,
                                    TCP_TABLE_BASIC_ALL,
                                    TCP_TABLE_OWNER_PID_LISTENER,
                                    TCP_TABLE_OWNER_PID_CONNECTIONS,
                                    TCP_TABLE_OWNER_PID_ALL,
                                    TCP_TABLE_OWNER_MODULE_LISTENER,
                                    TCP_TABLE_OWNER_MODULE_CONNECTIONS,
                                    TCP_TABLE_OWNER_MODULE_ALL
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_TCPTABLE_OWNER_PID
                                {
                                    public uint dwNumEntries;
                                    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
                                    public MIB_TCPROW_OWNER_PID[] table;
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_TCP6TABLE_OWNER_PID
                                {
                                    public uint dwNumEntries;
                                    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
                                    public MIB_TCP6ROW_OWNER_PID[] table;
                                }
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_TCPROW_OWNER_PID
                                {
                                    public uint state;
                                    public uint localAddr;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] localPort;
                                    public uint remoteAddr;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] remotePort;
                                    public uint owningPid;
                        
                                    public uint ProcessId
                                    {
                                        get { return owningPid; }
                                    }
                        
                                    public IPAddress LocalAddress
                                    {
                                        get { return new IPAddress(localAddr); }
                                    }
                        
                                    public ushort LocalPort
                                    {
                                        get
                                        {
                                            return BitConverter.ToUInt16(new byte[2] { localPort[1], localPort[0] }, 0);
                                        }
                                    }
                        
                                    public IPAddress RemoteAddress
                                    {
                                        get { return new IPAddress(remoteAddr); }
                                    }
                        
                                    public ushort RemotePort
                                    {
                                        get
                                        {
                                            return BitConverter.ToUInt16(new byte[2] { remotePort[1], remotePort[0] }, 0);
                                        }
                                    }
                        
                                    public MIB_TCP_STATE State
                                    {
                                        get { return (MIB_TCP_STATE)state; }
                                    }
                                }
                        
                        
                                [StructLayout(LayoutKind.Sequential)]
                                public struct MIB_TCP6ROW_OWNER_PID
                                {
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
                                    public byte[] localAddr;
                                    public uint localScopeId;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] localPort;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
                                    public byte[] remoteAddr;
                                    public uint remoteScopeId;
                                    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                                    public byte[] remotePort;
                                    public uint state;
                                    public uint owningPid;
                        
                                    public uint ProcessId
                                    {
                                        get { return owningPid; }
                                    }
                        
                                    public long LocalScopeId
                                    {
                                        get { return localScopeId; }
                                    }
                        
                                    public IPAddress LocalAddress
                                    {
                                        get { return new IPAddress(localAddr, LocalScopeId); }
                                    }
                        
                                    public ushort LocalPort
                                    {
                                        get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
                                    }
                        
                                    public long RemoteScopeId
                                    {
                                        get { return remoteScopeId; }
                                    }
                        
                                    public IPAddress RemoteAddress
                                    {
                                        get { return new IPAddress(remoteAddr, RemoteScopeId); }
                                    }
                        
                                    public ushort RemotePort
                                    {
                                        get { return BitConverter.ToUInt16(remotePort.Take(2).Reverse().ToArray(), 0); }
                                    }
                        
                                    public MIB_TCP_STATE State
                                    {
                                        get { return (MIB_TCP_STATE)state; }
                                    }
                                }
                        
                        
                                public const int AF_INET = 2;    // IP_v4 = System.Net.Sockets.AddressFamily.InterNetwork
                                public const int AF_INET6 = 23;  // IP_v6 = System.Net.Sockets.AddressFamily.InterNetworkV6
                        
                                public static Task<List<MIB_TCPROW_OWNER_PID>> GetAllTCPConnectionsAsync()
                                {
                                    return Task.Run(() => GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET));
                                }
                        
                                public static List<MIB_TCPROW_OWNER_PID> GetAllTCPConnections()
                                {
                                    return GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET);
                                }
                        
                                public static Task<List<MIB_TCP6ROW_OWNER_PID>> GetAllTCPv6ConnectionsAsync()
                                {
                                    return Task.Run(()=>GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6));
                                }
                        
                                public static List<MIB_TCP6ROW_OWNER_PID> GetAllTCPv6Connections()
                                {
                                    return GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6);
                                }
                        
                                private static List<IPR> GetTCPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
                                {
                                    List<IPR> result = null;
                        
                                    IPR[] tableRows = null;
                                    int buffSize = 0;
                        
                                    var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
                        
                                    // how much memory do we need?
                                    uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                                    IntPtr tcpTablePtr = Marshal.AllocHGlobal(buffSize);
                        
                                    try
                                    {
                                        ret = GetExtendedTcpTable(tcpTablePtr, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
                                        if (ret != 0)
                                            return new List<IPR>();
                        
                                        // get the number of entries in the table
                                        IPT table = (IPT)Marshal.PtrToStructure(tcpTablePtr, typeof(IPT));
                                        int rowStructSize = Marshal.SizeOf(typeof(IPR));
                                        uint numEntries = (uint)dwNumEntriesField.GetValue(table);
                        
                                        // buffer we will be returning
                                        tableRows = new IPR[numEntries];
                        
                                        IntPtr rowPtr = (IntPtr)((long)tcpTablePtr + 4);
                                        for (int i = 0; i < numEntries; i++)
                                        {
                                            IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
                                            tableRows[i] = tcpRow;
                                            rowPtr = (IntPtr)((long)rowPtr + rowStructSize);   // next entry
                                        }
                                    }
                                    finally
                                    {
                                        result = tableRows?.ToList() ?? new List<IPR>();
                        
                                        // Free the Memory
                                        Marshal.FreeHGlobal(tcpTablePtr);
                                    }
                        
                                    return result;
                                }
                        
                                public static string GetTcpStateName(MIB_TCP_STATE state)
                                {
                                    switch (state)
                                    {
                                        case MIB_TCP_STATE.MIB_TCP_STATE_CLOSED:
                                            return "Closed";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_LISTEN:
                                            return "Listen";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_SYN_SENT:
                                            return "SynSent";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_SYN_RCVD:
                                            return "SynReceived";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_ESTAB:
                                            return "Established";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT1:
                                            return "FinWait 1";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT2:
                                            return "FinWait 2";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_CLOSE_WAIT:
                                            return "CloseWait";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_CLOSING:
                                            return "Closing";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_LAST_ACK:
                                            return "LastAck";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_TIME_WAIT:
                                            return "TimeWait";
                                        case MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB:
                                            return "DeleteTCB";
                                        default:
                                            return ((int)state).ToString();
                                    }
                                }
                        
                                private static readonly ConcurrentDictionary<string, string> DicOfIpToHostName = new ConcurrentDictionary<string, string>();
                        
                                public const string UnknownHostName = "Unknown";
                        
                                // ******************************************************************
                                public static string GetHostName(IPAddress ipAddress)
                                {
                                    return GetHostName(ipAddress.ToString());
                                }
                        
                                // ******************************************************************
                                public static string GetHostName(string ipAddress)
                                {
                                    string hostName = null;
                        
                                    if (!DicOfIpToHostName.TryGetValue(ipAddress, out hostName))
                                    {
                                        try
                                        {
                                            if (ipAddress == "0.0.0.0" || ipAddress == "::")
                                            {
                                                hostName = ipAddress;
                                            }
                                            else
                                            {
                                                hostName = Dns.GetHostEntry(ipAddress).HostName;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Debug.Print(ex.ToString());
                                            hostName = UnknownHostName;
                                        }
                        
                                        DicOfIpToHostName[ipAddress] = hostName;
                                    }
                        
                                    return hostName;
                                }
                        
                                // ************************************************************************
                                /// <summary>
                                /// Will search for the an active NetworkInterafce that has a Gateway, otherwise
                                /// it will fallback to try from the DNS which is not safe.
                                /// </summary>
                                /// <returns></returns>
                                public static NetworkInterface GetMainNetworkInterface()
                                {
                                    List<NetworkInterface> candidates = new List<NetworkInterface>();
                        
                                    if (NetworkInterface.GetIsNetworkAvailable())
                                    {
                                        NetworkInterface[] NetworkInterfaces =
                                            NetworkInterface.GetAllNetworkInterfaces();
                        
                                        foreach (
                                            NetworkInterface ni in NetworkInterfaces)
                                        {
                                            if (ni.OperationalStatus == OperationalStatus.Up)
                                                candidates.Add(ni);
                                        }
                                    }
                        
                                    if (candidates.Count == 1)
                                    {
                                        return candidates[0];
                                    }
                        
                                    // Accoring to our tech, the main NetworkInterface should have a Gateway 
                                    // and it should be the ony one with a gateway.
                                    if (candidates.Count > 1)
                                    {
                                        for (int n = candidates.Count - 1; n >= 0; n--)
                                        {
                                            if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
                                            {
                                                candidates.RemoveAt(n);
                                            }
                                        }
                        
                                        if (candidates.Count == 1)
                                        {
                                            return candidates[0];
                                        }
                                    }
                        
                                    // Fallback to try by getting my ipAdress from the dns
                                    IPAddress myMainIpAdress = null;
                                    IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                                    foreach (IPAddress ip in host.AddressList)
                                    {
                                        if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
                                        {
                                            myMainIpAdress = ip;
                                            break;
                                        }
                                    }
                        
                                    if (myMainIpAdress != null)
                                    {
                                        NetworkInterface[] NetworkInterfaces =
                                            NetworkInterface.GetAllNetworkInterfaces();
                        
                                        foreach (NetworkInterface ni in NetworkInterfaces)
                                        {
                                            if (ni.OperationalStatus == OperationalStatus.Up)
                                            {
                                                IPInterfaceProperties props = ni.GetIPProperties();
                                                foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                                                {
                                                    if (ai.Address.Equals(myMainIpAdress))
                                                    {
                                                        return ni;
                                                    }
                                                }
                                            }
                                        }
                                    }
                        
                                    return null;
                                }
                        
                                // ******************************************************************
                                /// <summary>
                                /// AddressFamily.InterNetwork = IPv4
                                /// Thanks to Dr. Wilys Apprentice at
                                /// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
                                /// using System.Net.NetworkInformation;
                                /// </summary>
                                /// <param name="mac"></param>
                                /// <param name="addressFamily">AddressFamily.InterNetwork = IPv4,  AddressFamily.InterNetworkV6 = IPv6</param>
                                /// <returns></returns>
                                public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
                                {
                                    NetworkInterface[] NetworkInterfaces =
                                        NetworkInterface.GetAllNetworkInterfaces();
                        
                                    foreach (NetworkInterface ni in NetworkInterfaces)
                                    {
                                        if (ni.GetPhysicalAddress().Equals(mac))
                                        {
                                            if (ni.OperationalStatus == OperationalStatus.Up)
                                            {
                                                IPInterfaceProperties props = ni.GetIPProperties();
                                                foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
                                                {
                                                    if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
                                                    {
                                                        if (ai.Address.AddressFamily == addressFamily)
                                                        {
                                                            return ai.Address;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                        
                                    return null;
                                }
                        
                                // ******************************************************************
                                /// <summary>
                                /// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call 
                                /// '?.ToString() ?? ""' on the result.
                                /// </summary>
                                /// <returns></returns>
                                public static IPAddress GetMyInternetIpAddress()
                                {
                                    NetworkInterface ni = GetMainNetworkInterface();
                                    IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
                                    if (ipAddress == null) // could it be possible ?
                                    {
                                        ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
                                    }
                        
                                    return ipAddress;
                                }
                        
                                // ******************************************************************
                                public static bool IsBroadcastAddress(IPAddress ipAddress)
                                {
                                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        return ipAddress.GetAddressBytes()[3] == 255;
                                    }
                        
                                    if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
                                    {
                                        return false; // NO broadcast in IPv6
                                    }
                        
                                    return false;
                                }
                        
                                // ******************************************************************
                                public static bool IsMulticastAddress(IPAddress ipAddress)
                                {
                                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                                    {
                                        // Source: https://technet.microsoft.com/en-us/library/cc772041(v=ws.10).aspx
                                        return ipAddress.GetAddressBytes()[0] >= 224 && ipAddress.GetAddressBytes()[0] <= 239;
                                    }
                        
                                    if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
                                    {
                                        return ipAddress.IsIPv6Multicast;
                                    }
                        
                                    return false;
                                }
                        
                                // ******************************************************************
                        
                            }
                        }
                        

                        【讨论】:

                          【解决方案24】:

                          另一种获取公共 IP 地址的方法是使用 OpenDNS 的 resolve1.opendns.com 服务器并将 myip.opendns.com 作为请求。

                          在命令行上是:

                            nslookup myip.opendns.com resolver1.opendns.com
                          

                          或者在 C# 中使用 DNSClient nuget:

                            var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
                            var result = lookup.Query("myip.opendns.com", QueryType.ANY);
                          

                          这比点击 http 端点和解析响应要干净一些。

                          【讨论】:

                            【解决方案25】:

                            这是在 VB.NET 中以 csv 格式获取所有本地 IP

                            Imports System.Net
                            Imports System.Net.Sockets
                            
                            Function GetIPAddress() As String
                                Dim ipList As List(Of String) = New List(Of String)
                                Dim host As IPHostEntry
                                Dim localIP As String = "?"
                                host = Dns.GetHostEntry(Dns.GetHostName())
                                For Each ip As IPAddress In host.AddressList
                                    If ip.AddressFamily = AddressFamily.InterNetwork Then
                                        localIP = ip.ToString()
                                        ipList.Add(localIP)
                                    End If
                                Next
                                Dim ret As String = String.Join(",", ipList.ToArray)
                                Return ret
                            End Function
                            

                            【讨论】:

                              【解决方案26】:

                              以最快的方式获取远程 IP 地址。您必须使用下载器,或在您的计算机上创建服务器。

                              使用这个简单代码的缺点:(推荐)是需要 3-5 秒才能获取您的远程 IP 地址,因为初始化时 WebClient 总是需要 3-5 秒来检查您的代理设置。

                               public static string GetIP()
                               {
                                          string externalIP = "";
                                          externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
                                          externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                                                         .Matches(externalIP)[0].ToString();
                                          return externalIP;
                               }
                              

                              这是我修复它的方法..(第一次仍然需要 3-5 秒)但之后它总是会在 0-2 秒内获得您的远程 IP 地址,具体取决于您的连接。

                              public static WebClient webclient = new WebClient();
                              public static string GetIP()
                              {
                                  string externalIP = "";
                                  externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
                                  externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                                                 .Matches(externalIP)[0].ToString();
                                  return externalIP;
                              }
                              

                              【讨论】:

                              • 为什么投反对票?你找不到比这更快或更好的答案。每次初始化 WebClient 都会产生很大的开销延迟。
                              【解决方案27】:
                              private static string GetLocalIpAdresse()
                                  {
                                      var host = Dns.GetHostEntry(Dns.GetHostName());
                                      foreach(var ip in host.AddressList)
                                      {
                                          if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                          {
                                              return ip.ToString();
                                          }
                                      }
                                      throw new Exception  ("No network adapters with an IPv4 address in the system");
                                  }
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 2011-02-07
                                • 2018-02-23
                                • 1970-01-01
                                • 2018-08-03
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多