我在asp.net应用程序中有一些代码需要获取客户端计算机的ipv4地址(用户都在我们自己的网络上).最近我们将应用程序运行的服务器升级到Windows 2008服务器.现在,当客户端在较旧的操作系统上时,Request.UserHostAddress代码返回ipv4,而当它们在较新的操作系统(Vista和更高版本)上时,返回ipv6.因此,依赖于此的功能适用于某些客户而非其他客户.
我添加了应该从ipv6转换为ipv4的代码,以尝试解决此问题.这是来自这个在线教程:http://www.4guysfromrolla.com/articles/071807-1.aspx.我正在使用dsn.GetHostAddress然后循环返回的IP寻找一个"InterNetwork"
foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress)) { if (IPA.AddressFamily.ToString() == "InterNetwork") { IP4Address = IPA.ToString(); break; } } if (IP4Address != String.Empty) { return IP4Address; } foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName())) { if (IPA.AddressFamily.ToString() == "InterNetwork") { IP4Address = IPA.ToString(); break; } } return IP4Address;
问题是这不适合我.从ipv4连接的客户端继续返回客户端计算机的正确ipv4 IP,但是从Vista和Windows 7连接的客户端返回SERVER计算机的ipv4 IP而不是客户端计算机.
简单回答:在服务器上禁用IPV6,或从DNS条目中删除服务器的IPV6地址.
没有神奇的IPV4 < - > IPV6转换器.它们是完全不同的协议,一个地址不转换为另一个.如果要可靠地检索客户端的IPV4地址,则需要确保客户端通过IPV4连接.
我也复制了示例代码,一位同事指出它显然是错误的.此行使用服务器的主机名,因此结果不正确:
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
我更正了项目中的代码如下:
////// Returns the IPv4 address of the specified host name or IP address. /// /// The host name or IP address to resolve. ///The first IPv4 address associated with the specified host name, or null. public static string GetIPv4Address(string sHostNameOrAddress) { try { // Get the list of IP addresses for the specified host IPAddress[] aIPHostAddresses = Dns.GetHostAddresses(sHostNameOrAddress); // First try to find a real IPV4 address in the list foreach (IPAddress ipHost in aIPHostAddresses) if (ipHost.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) return ipHost.ToString(); // If that didn't work, try to lookup the IPV4 addresses for IPV6 addresses in the list foreach (IPAddress ipHost in aIPHostAddresses) if (ipHost.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { IPHostEntry ihe = Dns.GetHostEntry(ipHost); foreach (IPAddress ipEntry in ihe.AddressList) if (ipEntry.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) return ipEntry.ToString(); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex); } return null; }
上面的代码适用于Windows 7/Server 2008上的ASP.Net 2.0.希望这会有所帮助.