.NET获得IP地址
目录
ASP.NET Framework获得客户端IP地址
/// <summary> /// 获取访问者IP地址 /// </summary> /// <returns></returns> string GetHostAddress() { string userIP = "127.0.0.1"; try { if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.ServerVariables == null) return ""; string CustomerIP = ""; //CDN加速后取到的IP CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"]; if (!string.IsNullOrEmpty(CustomerIP)) { return CustomerIP; } CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!String.IsNullOrEmpty(CustomerIP)) return CustomerIP; if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) { CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (CustomerIP == null) CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } else { CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.Compare(CustomerIP, "unknown", true) == 0) return System.Web.HttpContext.Current.Request.UserHostAddress; return CustomerIP; } catch { } return userIP; } /// <summary> /// 检查IP地址格式 /// </summary> /// <param name="ip"></param> /// <returns></returns> bool IsIP(string ip) { return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); }
GarsonZhang www.yesdotnet.com
使用:
public ActionResult Index(string systype) { var ip = GetHostAddress(); }
GarsonZhang www.yesdotnet.com
二、
public static class HttpRequestMessageExtensions { private const string HttpContext = "MS_HttpContext"; private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; private const string OwinContext = "MS_OwinContext"; public static string GetClientIpAddress(this HttpRequestMessage request) { // Web-hosting. Needs reference to System.Web.dll if (request.Properties.ContainsKey(HttpContext)) { dynamic ctx = request.Properties[HttpContext]; if (ctx != null) { return "" + ctx.Request.UserHostAddress; } } // Self-hosting. Needs reference to System.ServiceModel.dll. if (request.Properties.ContainsKey(RemoteEndpointMessage)) { dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage]; if (remoteEndpoint != null) { return "" + remoteEndpoint.Address; } } // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll. if (request.Properties.ContainsKey(OwinContext)) { dynamic owinContext = request.Properties[OwinContext]; if (owinContext != null) { return "" + owinContext.Request.RemoteIpAddress; } } return null; } }
GarsonZhang www.yesdotnet.com
.NET获得本机外网IP地址
private void btn_GetIP_Click(object sender, EventArgs e) { string url = "https://ip.cn/api/index?ip=&type=0"; try { string result = GetUrl(url); string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"; string ip = Regex.Match(result, pattern).ToString(); txt_IP.Text = ip; } catch (Exception ex) { throw ex; } } private string GetUrl(string url) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true; request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } request.Method = "GET"; //使用get方式发送数据 request.ContentType = "application/x-www-form-urlencoded"; request.Referer = null; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; //获取网页响应结果 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string result = string.Empty; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; }
GarsonZhang www.yesdotnet.com
.net Core
.NET Core 获得服务器本地的IP地址:注意,不是获得客户端IP地址
string IP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();
GarsonZhang www.yesdotnet.com
注意,此方法不能获得本机的外网IP地址,如果要获得本机外网IP地址,请使用请求url的方式 参考: .NET获得本机外网IP地址
.NET Core 获得客户端IP地址:
/// <summary> /// 扩展类 /// </summary> public static class Extension { /// <summary> /// 获取客户Ip /// </summary> /// <param name="context"></param> /// <returns></returns> public static string GetClientUserIp(this HttpContext context) { var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = context.Connection.RemoteIpAddress.ToString(); } return ip; } }
GarsonZhang www.yesdotnet.com
使用:
string IP = HttpContext.GetClientUserIp();
GarsonZhang www.yesdotnet.com
解决Asp.Net Core2.0发布到Ubuntu后不能正确获取客户IP解决办法
/// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="loggerFactory"></param> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { #region 解决Ubuntu Nginx 代理不能获取IP问题 app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); #endregion }
GarsonZhang www.yesdotnet.com
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post YES开发框架