/// <summary> /// Retrieves the IP address of the current request -- handles proxies and private networks. /// </summary> /// <param name="serverVariables">The server variables collection to extract the IP from.</param> public static string GetRemoteIP(this NameValueCollection serverVariables) { var ip = serverVariables["REMOTE_ADDR"]; // could be a proxy -- beware var forwardedFor = serverVariables["HTTP_X_FORWARDED_FOR"] ?? ""; var remoteIPs = forwardedFor.Split(_commaSpace, StringSplitOptions.RemoveEmptyEntries); // Loop from the end until we get the first IP that's *not* internal: for (var i = remoteIPs.Length - 1; i >= 0; i--) { var remoteIp = remoteIPs[i]; // Nothing? Toss it. if (remoteIp == null) { continue; } // Not valid? Toss it. if (!IPNet.TryParse(remoteIp, out IPNet remoteIpNet)) { continue; } // Usual prod behavior: Never match a private address, unless it's the last. // Get the first IP outside current networks. // Take the first external IP we match, or the last IP we match - e.g. from another web server if (!remoteIpNet.IsPrivate || i == 0) { ip = remoteIp; break; } } return(ip.HasValue() ? ip : UnknownIP); }
public bool Contains(IPNet network) { return(network != null && AddressFamily == network.AddressFamily && TinyFirstAddressInSubnet <= network.TinyFirstAddressInSubnet && network.TinyLastAddressInSubnet <= TinyLastAddressInSubnet); //return (TSubnet & TIPAddress) == (TSubnet & network.TIPAddress & TIPAddress ); }
public static bool TryParse(string ipOrCidr, out IPNet net) { try { net = Parse(ipOrCidr); return(true); } catch { net = null; return(false); } }
public static bool IsPrivateNetwork(IPNet network) { return(ReservedPrivateRanges.Any(r => r.Contains(network))); }