有没有一行代码可以获取服务器的IP地址?
谢谢。
Request.ServerVariables["LOCAL_ADDR"];
从文档中得知:
返回接收请求的服务器地址。在计算机上可以绑定多个IP地址的情况下非常重要,您需要找出请求使用了哪个地址。
这与远程地址有所不同,后者涉及客户机器。
LOCAL_ADDR
返回托管站点关联的网络地址 - REMOTE_ADDR
返回请求客户端的地址:"REMOTE_ADDR
请求方远程主机的 IP 地址。" - Zhaph - Ben Duguid我在网上搜索到以下代码:(我找不到单行方法)
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();
// Show the IP
MessageBox.Show(myIP);
->其中index是您IP地址主机的索引(即网络连接)。
代码来源:http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
正如其他人所发表的,System.Net.Dns.GetHostEntry
是正确的方法。当您访问 AddressList
属性时,您需要考虑到 AddressFamily
属性,因为它可能返回 IPv4 和 IPv6 的结果。
当您在个人电脑上运行此代码时,此方法将返回您的机器公共IP地址;而当您在服务器上部署应用程序时,它将返回服务器IP地址。
public static string Getpublicip()
{
try
{
string externalIP = "";
var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
externalIP = new WebClient().DownloadString("http://icanhazip.com");
return externalIP;
}
catch (Exception e)
{
return "null";
}
}
HttpRequestMessage
对象而不是经典的HttpRequest
时如何进行操作。 - SandRockMS_HttpContext
属性,然后将其转换为HttpContextBase
,从而允许访问ServerVariables
属性。根据您执行此操作的位置,您还可以直接获取 HttpContext 并查询HttpContext.Current.Request.ServerVariables ["LOCAL_ADDR"]
(很抱歉回复晚了 ;)) - Zhaph - Ben Duguid