获取服务IP
获取服务器IP,可以通过下面两种途径获取:
1、Request.ServerVariables[LOCAL_ADDR]
Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.
HttpRequest.ServerVariables 属性:获取 Web 服务器变量的集合,对于 IIS 支持的服务器变量的列表(http://msdn.microsoft.com/zh-cn/library/ms524602(vs.90).aspx)。
命名空间:System.Web 程序集:System.Web(在 system.web.dll 中)
这个方法使用有时候不是那么靠谱,以下是ServerVariables的实现,还是不明白是如何获取到服务器IP的,为什么在不同的服务器有的是获取到真实的ip,而有的是获取到127.0.0.1,具体到底是跟IIS哪项设置有关?有望大神帮忙点解下。
public NameValueCollection ServerVariables { get { if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low)) { return this.GetServerVars(); } return this.GetServerVarsWithDemand(); } } private NameValueCollection GetServerVars() { if (this._serverVariables == null) { this._serverVariables = new HttpServerVarsCollection(this._wr, this); if (!(this._wr is IIS7WorkerRequest)) { this._serverVariables.MakeReadOnly(); } } return this._serverVariables; } internal HttpServerVarsCollection(HttpWorkerRequest wr, HttpRequest request) : base(0x3b) { this._iis7workerRequest = wr as IIS7WorkerRequest; this._request = request; this._populated = false; }
2、Dns.GetHostAddresses
返回指定主机的 Internet 协议 (IP) 地址。
命名空间: System.Net
程序集: System(在 System.dll 中)
GetHostAddresses 方法在 DNS 服务器中查询与某个主机名关联的 IP 地址。如果 hostNameOrAddress 是 IP 地址,则不查询 DNS 服务器直接返回此地址。当空字符串作为主机名传递时,对于除 Windows Server 2003 以外的所有操作系统,此方法都返回本地主机的 IPv4 地址;对于 Windows Server 2003,则同时返回本地主机的 IPv4 和 IPv6 地址(这个msdn注释觉得有点问题,请看下面代码结果)。如果本地计算机上没有安装 IPv6,就会从 GetHostAddresses 方法的结果中筛选掉 IPv6 地址。结果,只要生成的 IPv6 可用于参数 hostNameOrAddress,就可能返回一个空的 IPAddress 实例。
运行环境:win7以及windows server 2008
static void Main(string[] args) { var serverIP = Dns.GetHostAddresses(""); Console.WriteLine("GetHostAddresses({0}) returns:", serverIP); foreach (IPAddress ip in serverIP) { Console.WriteLine(" {0}", ip); } Console.ReadLine(); }
Dns.GetHostAddresses() return a strange address "::1"
The address ::1 is the IPv6 equivalent of 127.0.0.1 in IPv4, i.e it's a loopback address. Its presence simply indicates that you enabled IPv6 on your NIC (that's the default since Windows Vista).
If you don't want to handle IPv6 addresses, you can check the AddressFamily property of the IPAddress returned; it will contain the value AddressFamily.InterNetworkV6 for IPv6 and AddressFamily.InterNetwork for IPv4
这个方法获取到的IP包含了IP6以及IP4的ip,所以如果只想获取ip4所对应的ip,需要进行处理下,或者用微软废弃的方法Dns.GetHostByName(Dns.GetHostName())
static void Main(string[] args) { var serverIP = Dns.GetHostByName(Dns.GetHostName()).AddressList; Console.WriteLine("GetHostAddresses({0}) returns:", serverIP); foreach (IPAddress ip in serverIP) { Console.WriteLine(" {0}", ip); } Console.ReadLine(); }