ASP.NET Core – get client IP and its long value

In your ASP.NET Core application, mostly you want to get client IP for some purpose, for example, logging or check if IP is in some range.

You can get client IP from controller:

Request?.HttpContext?.Connection?.RemoteIpAddress?

and if want IPv4 format:

Request?.HttpContext?.Connection?.RemoteIpAddress?.MapToIPv4()

and if want IP string:

Request?.HttpContext?.Connection?.RemoteIpAddress?.MapToIPv4()?.ToString()

To get the long value of IP address, there is a property Address

Request?.HttpContext?.Connection?.RemoteIpAddress?.MapToIPv4()?.Address

But this property is deprecated:

[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")]
public long Address { get; set; }

Instead, we need to use another approach to get IP address long value:

BitConverter.ToUInt32(Request?.HttpContext?.Connection?.RemoteIpAddress?.MapToIPv4()?.GetAddressBytes()?.Reverse()?.ToArray())

Leave a comment