在ASP.NET中获取服务器的IP地址?

问题描述 投票:31回答:5

如何获取调用ASP.NET页面的服务器的IP地址?我见过有关Response对象的内容,但在c#中我是新手。万分感谢。

c# asp.net dns referrer
5个回答
55
投票

这应该工作:

 //this gets the ip address of the server pc

  public string GetIPAddress()
  {
     IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated.
     IPAddress ipAddress = ipHostInfo.AddressList[0];

     return ipAddress.ToString();
  }

http://wec-library.blogspot.com/2008/03/gets-ip-address-of-server-pc-using-c.html

要么

 //while this gets the ip address of the visitor making the call
  HttpContext.Current.Request.UserHostAddress;

http://www.geekpedia.com/KB32_How-do-I-get-the-visitors-IP-address.html


32
投票

Request.ServerVariables["LOCAL_ADDR"];

这为多宿主服务器提供了IP请求


14
投票

以上是缓慢的,因为它需要DNS调用(如果一个不可用,显然不会工作)。您可以使用下面的代码获取当前pc的本地IPV4地址及其对应的子网掩码的映射:

public static Dictionary<IPAddress, IPAddress> GetAllNetworkInterfaceIpv4Addresses()
{
    var map = new Dictionary<IPAddress, IPAddress>();

    foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
    {
        foreach (var uipi in ni.GetIPProperties().UnicastAddresses)
        {
            if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;

            if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
            map[uipi.Address] = uipi.IPv4Mask;
        }
    }
    return map;
}

警告:尚未在Mono中实现


7
投票
  //this gets the ip address of the server pc
  public string GetIPAddress()
  {
     string strHostName = System.Net.Dns.GetHostName();
     //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); <-- Obsolete
     IPHostEntry ipHostInfo = Dns.GetHostEntry(strHostName);
     IPAddress ipAddress = ipHostInfo.AddressList[0];

     return ipAddress.ToString();
  }

3
投票

这适用于IPv4:

public static string GetServerIP()
{            
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

    foreach (IPAddress address in ipHostInfo.AddressList)
    {
        if (address.AddressFamily == AddressFamily.InterNetwork)
            return address.ToString();
    }

    return string.Empty;
}
© www.soinside.com 2019 - 2024. All rights reserved.