简体   繁体   中英

How do I get the server/website IP address in asp.net?

When a user request comes in, I can use Context.Request.UserHostAddress to get the user's IP address. How can I get the IP address of the website/server at runtime? I have some reporting code that can be used by multiple websites on the same server, and each website uses a different IP address. So I need to be able to detect the website's IP address at runtime.

System.Net.Dns.GetHostAddresses

by the way, you must pass in as an argument the name of the host, so perhaps try this:

System.Net.Dns.GetHostByAddress(System.Net.IPAddress.Parse(System.Web.HttpContext.Current.Request.UserHostName)).HostName;

And if all else fails, just do it the old school way:

Response.Write(Request.ServerVariables["LOCAL_ADDR"]);

Thanks Alex, your answer put me on the right path. Here is the code to do what I am looking for:

VB.NET:

System.Net.Dns.GetHostAddresses(Request.Url.Host)(0).ToString()

or

System.Net.Dns.GetHostEntry(Request.Url.Host).AddressList(0).ToString()
     string siteName = "Your Site URL";
     string tempUrl = siteName.Replace("http://", "").Replace("https://", "").Trim();
     string[] SiteURLArr = tempUrl.Split('/');
     string SiteURL = SiteURLArr[0];
      System.Net.IPAddress[] ip = System.Net.Dns.GetHostAddresses(SiteURL);
     Response.Write(ip[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM