程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> .NET獲取IP返回::1的解決辦法

.NET獲取IP返回::1的解決辦法

編輯:關於.NET
剛剛測試程序,一個功能要求獲取客戶端IP,然而在本機測試過程中發現,客戶端(本機)IP始終返回::1,獲取 IP 部份的代碼如下:

private string GetIP()
{
string result = String.Empty;

result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}

if (null == result || result == String.Empty || !IsIP(result))
{
result = "0.0.0.0";
}

return result;

}

public static bool IsIP(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}


於是最終獲取倒的是因無法匹配而返回的默認IP 0.0.0.0

google了一下,沒有結果。

繼續想辦法。發現不影響獲取其它客戶端(非本機)IP。根據此現象,我想應該是localhost引起的,於是查看host映射,果然發現::1

(Host映射查看方法 C:\Windows\System32\drivers\etc 文件hosts)


# Copyright (c) 1993-2006 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 sosoft.cnblogs.com # source server
# 38.25.63.10 roucheng.cnblogs.com # x client host

127.0.0.1 localhost
::1 localhost

原來是因為操作系統開啟了IPV6,它對localhost進行了映射的原因。如果我們需要獲取的IP是IPV4的,那麼可以刪掉::1映射。

如果將來我們需要獲取的是IPV6的IP,那麼就需要這樣的映射。然後程序裡統一實現獲取IPv6的代碼。


或者:
1。Dns.GetHostByName("").AddressList[0].ToString();

2、 string localIP = "";
foreach (IPAddress ip in Dns.GetHostAddresses(""))
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved