【问题标题】:How to get an IP address in C# code [duplicate]如何在 C# 代码中获取 IP 地址 [重复]
【发布时间】:2011-04-03 21:28:19
【问题描述】:

可能重复:
How to get my own IP address in C#?

我需要通过 C# 代码获取运行应用程序的系统的 IP 地址

IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());   
foreach (IPAddress theaddress in ip)
{
    String _ipAddress = theaddress.ToString();
}

我正在使用此代码,但这会在不同的操作系统中给出不同的结果。例如,在 Windows 7 中,它给出“fe80::e3:148d:6e5b:bcaa%14”
而 Windows XP 则给出“192.168.10.93”。

【问题讨论】:

标签: c#


【解决方案1】:

请注意,您可能有多个 IP 地址分配给一台机器。您可以像这样检索它们(注意:此代码忽略环回地址):

  var iplist = new List<string>();
  foreach (var iface in NetworkInterface.GetAllNetworkInterfaces())
  {
    var ips = iface.GetIPProperties().UnicastAddresses;
    foreach (var ip in ips)
      if (ip.Address.AddressFamily == AddressFamily.InterNetwork &&
          ip.Address.ToString() != "127.0.0.1")
        iplist.Add(ip.Address.ToString());
  }

使用的命名空间包括:

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2013-12-30
    • 2020-12-28
    相关资源
    最近更新 更多