I'm trying to get the user's IP address from ASP.NET MVC 5. I've looked up various examples, such as these:
- https://stackoverflow.com/a/740431/177416
- https://stackoverflow.com/a/20194511/177416
- https://stackoverflow.com/a/3003254/177416
They've all produced the same result: the user is considered internal to the network. I've had friends try their phones (which are not on the network). Here's my latest attempt:
private static Logger _logger = LogManager.GetCurrentClassLogger();
public static bool IsIpInternal()
{
var ipAddress = HttpContext.Current.Request.UserHostAddress;
var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, ipAddress);
_logger.Log(logEvent);
try
{
if (ipAddress != null)
{
var ipParts = ipAddress.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
var isDebug = System.Diagnostics.Debugger.IsAttached;
if (ipParts[0] == 10)
{
return true;
}
}
}
catch (Exception e)
{
logEvent = new LogEventInfo(LogLevel.Error, _logger.Name, e.Message);
_logger.Log(logEvent);
return false;
}
return false;
}
The log is showing 10.xxx.xx.xxx
for all requests (based on the log). This is an internal address rather than the IP of the client connecting to the web app. The IsIpInternal()
returns true always. What am I doing wrong?
Note that I'm ignoring 192.168.x.x
and 172.16.xxx.xxx
addresses as being internal.