如何获取运行我的C#应用程序的服务器的IP地址?

373

我正在运行一个服务器,并且希望显示我的自身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;

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


1
关于外部IP地址,我不认为有一种本地方法可以检索它。localhost可能在NAT路由器后面,将本地网络地址转换为公共地址。有没有(本地)方法可以验证是否是这种情况?我不知道任何方法... - Thiago Arrais
该示例使用 DNS 获取 IP 地址,我曾经遇到过 DNS 信息错误的情况。对于这种情况,示例可能会回复 错误 信息。 - leiflundgren
@leiflundgren 我也曾经遇到 DNS 信息错误的情况。当我面对这种情况时,我的回答描述了我如何在不依赖 DNS 的情况下获得所需的 IP 地址。 - Dr. Wily's Apprentice
13
使用LINQ:Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First().ToString() - Luis Perez
2
这是一个典型的情况,不同需求的用户往往会问相同的问题。有些人想知道如何从公共网络访问他们的计算机。规范答案是 STUN,尽管许多人会提供依赖于随机第三方的黑客解决方案。有些人只想知道他们在本地网络上的 IP 地址。在这种情况下,好的答案会提到 NetworkInterface.GetAllNetworkInterfaces Method - Stéphane Gourichon
27个回答

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

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

1

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

1

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

在命令行上,可以这样做:

  nslookup myip.opendns.com resolver1.opendns.com

或者使用DNSClient NuGet包在C#中:

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

这比访问HTTP端点和解析响应要更清晰一些。

0
为了尽快获取远程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都会有很大的开销延迟,这是无法避免的。 - SSpoke

0

这是使用VB.NET获取所有本地IP地址并以CSV格式输出的方法。

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

0
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");
    }

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