Home > front end >  Get User's Ip address using ASP.NET Core 3.1 Web API
Get User's Ip address using ASP.NET Core 3.1 Web API

Time:10-06

I'm using ASP.NET Core 3.1 Web API. I'd like to get the user's Ip address. I have been stuck for a long time, please help me, thank you so much!

CodePudding user response:

In the controller you can call :

var remoteIpAddress = HttpContext.Connection.RemoteIpAddress.ToString();

You could have obtained an answer by a simple Google search.

CodePudding user response:

@Abdelkrim's answer is sufficient if you want to use IPv6 addresses, which are more unique by definition and therefore more secure. However IPv4 addresses are still more common than IPv6 so it becomes an accessibility versus security problem (accessibility wins btw, don't want your app inaccessible to half the world).

To use IPv4 addresses however, you can simply extend the code in Abdelkrim's answer as follows:

var ipv4 = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

That will return any IP address as ^[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}, i.e. as IPv4 format.

As for your confusion with your localhost IP address: When developing any app which runs on a network (an API, website, et cetera) locally, the instance will run inside your PC so to speak. This inside of your PC is represented by the ::1 IP address, or 0.0.0.1, or 0:0:0:0:0:1. The more commonly known localhost address is 127.0.0.1.

This address is completely restricted to your own system and does not communicate with the outside.

The command ipconfig in cmd returns the IP address your PC uses to communicate with the outside. This IP address is completely unrelated to localhost, nor do either care about each other's existence.

So, the website you used to get your PC's IP address will return the one your PC uses to communicate with the outside world (the one returned by ipconfig as well), not your localhost IP.

Hopefully the answer for your coding problem is helpfull and the explanation about localhost is clear!

  • Related