Reputation: 10259
Currently the same website is running under two different server configurations and under two different URLs.
For convenience it would be nice to have the same code running on all servers as it will simplify deployment procedures.
I know that I can do things like this:
if (string.Equals(HttpContext.Current.Request.Headers["X-Forwarded-Proto"], "https"))
This checks if the load balancer forwarded 'https' data. However, what I want to do is simply detect if a load balancer exists or not.
Essential I want to write: if(LoadBalancerExists) { do this stuff }
Does anyone know how to do this?
Upvotes: 1
Views: 1612
Reputation: 10259
It turns out that if the load balancer does not exist Request.Headers["X-Forwarded-Proto"] == null
.
If it does exist Request.Headers["X-Forwarded-Proto"] == 'http' or 'https'
Quick Solution: if(Request.Headers["X-Forwarded-Proto"] == null) { do stuff }
Updated Solution with added security since headers can be spoofed:
ClientIP = Request.UserHostAddress;
Subnet = <enter your aws CIDR subnet address>; // e.g. 172.0.0.0
Mask = <enter your aws VPC address>; // e.g. 255.255.0.0
// Verify header
if(Request.Headers["X-Forwarded-Proto"] == null) {
// Verify that ClientIP i.e. the LoadBalancer's IP is inside of our subnet.
if(IsAddressOnSubnet(ClientAddress, Subnet, Mask)) {
// do some stuff
}
}
protected bool IsAddressOnSubnet(IPAddress Address, IPAddress Subnet, IPAddress Mask)
{
try
{
Byte[] addressOctets = Address.GetAddressBytes();
Byte[] subnetOctets = Mask.GetAddressBytes();
Byte[] networkOctets = Subnet.GetAddressBytes();
return
((networkOctets[0] & subnetOctets[0]) == (addressOctets[0] & subnetOctets[0])) &&
((networkOctets[1] & subnetOctets[1]) == (addressOctets[1] & subnetOctets[1])) &&
((networkOctets[2] & subnetOctets[2]) == (addressOctets[2] & subnetOctets[2])) &&
((networkOctets[3] & subnetOctets[3]) == (addressOctets[3] & subnetOctets[3]));
}
catch (System.Exception ex)
{
return false;
}
}
Thanks to Michael-sqlbot for pointing out the security issue.
This aws reference is useful.
Reference for detecting that ip address is on subnet here thanks to Спасибо! Прекрасное решение!.
Upvotes: 1