public static IEnumerable <IPAddress> GetRemoteIPAddresses(this HttpContext httpContext) { var result = new List <IPAddress>(); if (httpContext.Connection.RemoteIpAddress != null) { result.Add(httpContext.Connection.RemoteIpAddress); } string failed = null; if (httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var ipList) && ipList.Any()) { var ips = ipList.Select(x => x.Split(",")).SelectMany(x => x).Where(x => !string.IsNullOrWhiteSpace(x)); foreach (var ip in ips) { if (CreyIPAddress.TryParse(ip, out var parsed)) { result.Add(parsed); } else if (failed == null) { failed = string.Join(",", ips); } } } if (!result.Any() && failed != null) { throw new InvalidArgumentException($"Failed to parse IP from one of:'{failed}'"); } return(result); }
public async Task <GeoLocation> GetLocation(string ipAddress) { return(CreyIPAddress.TryParse(ipAddress, out var ip) ? await GetLocation(ip) : null); }