Beispiel #1
0
        /// <exception cref="InvalidArgumentException">Fail</exception>
        private static IEnumerable <IPAddress> GetRemoteIPAddresses(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)
                {
                    // ISSUE: .NET Core 5 has proper attributes for this pattern `when true than not null` then no warning, but with standard need to `!`
                    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 void Parse()
        {
            IPAddress _;

            Assert.True(CreyIPAddress.TryParse("::ffff:10.65.0.11", out _));
            Assert.Equal(_, IPAddress.Parse("10.65.0.11"));
            Assert.True(CreyIPAddress.TryParse("1fff:0:a88:85a3::ac1f:42", out _));
            Assert.True(CreyIPAddress.TryParse("127.0.0.1", out _));
            Assert.Equal(_, IPAddress.Parse("127.0.0.1"));
            Assert.True(CreyIPAddress.TryParse("127.0.0.1:42", out _));
            Assert.Equal(_, IPAddress.Parse("127.0.0.1"));
            Assert.True(CreyIPAddress.TryParse("  127.0.0.1 ", out _));
            Assert.True(CreyIPAddress.TryParse("  127.0.0.1:42   ", out _));
            Assert.Equal(_, IPAddress.Parse("127.0.0.1"));
            Assert.True(CreyIPAddress.TryParse("1fff:0:a88:85a3::ac1f", out _));
            Assert.Equal(_, IPAddress.Parse("1fff:0:a88:85a3::ac1f"));
            Assert.True(CreyIPAddress.TryParse("[1fff:0:a88:85a3::ac1f]", out _));
            Assert.Equal(_, IPAddress.Parse("1fff:0:a88:85a3::ac1f"));

            Assert.True(CreyIPAddress.TryParse("fe80::1ff:fe23:4567:890a%3", out _));

            Assert.True(CreyIPAddress.TryParse("[1fff:0:a88:85a3::ac1f]:42", out _));
            Assert.Equal(_, IPAddress.Parse("1fff:0:a88:85a3::ac1f"));

            Assert.True(CreyIPAddress.TryParse(" [1fff:0:a88:85a3::ac1f]:42 ", out _));
            Assert.Equal(_, IPAddress.Parse("1fff:0:a88:85a3::ac1f"));
        }