我如何调用我的ASP.NET页面的服务器的IP地址?我所看到的东西,约一个Response对象,但我在C#很新。由于一吨。

有帮助吗?

解决方案

此应该工作:

 //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

OR

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

HTTP://www.geekpedia。 COM / KB32_How-DO-I-得到最游客-IP-address.html

其他提示

Request.ServerVariables["LOCAL_ADDR"];

这给出了IP请求排在对多宿主服务器

以上是慢,因为它需要一个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;
}

警告:这没有在单声道实现还

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

这将对于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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top