IIS 7.0 之後
用 HttpContext.Current.Request.UserHostAddress 抓的IP會是
類似 fe80::b148:cddc:81cd:fd10%2
這樣的IPv6 位址
如果要抓 IPv4 要特別改寫
參考
https://dotblogs.com.tw/hunterpo/2011/03/21/21991
HttpContext.Current.Request.UserHostAddress
暫時的替代方法
public static string GetClientIPv4() { string ipv4 = String.Empty; foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP())) { if (ip.AddressFamily.ToString() == "InterNetwork") { ipv4 = ip.ToString(); break; } } if (ipv4 != String.Empty) { return ipv4; } // 原作使用 Dns.GetHostName 方法取回的是 Server 端資訊,非 Client 端。 // 改寫為利用 Dns.GetHostEntry 方法,由獲取的 IPv6 位址反查 DNS 紀錄, // 再逐一判斷何者屬 IPv4 協定,即可轉為 IPv4 位址。 foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList) //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName())) { if (ip.AddressFamily.ToString() == "InterNetwork") { ipv4 = ip.ToString(); break; } } return ipv4; } /// <summary> /// 取得客戶端主機位址 /// </summary> public static string GetClientIP() { if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"]) { return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } else { return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } }