Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the client's IP address

Previously in other version of asp.net, I used these properties of HttpRequest:

Request.ServerVariables["REMOTE_ADDR"]
Request.UserHostAddress

How can I achieve the same in ASP.NET Core?

like image 216
Dalsier Avatar asked Dec 18 '15 15:12

Dalsier


People also ask

How can we get the IP address of the client?

Determining IP Address using $_SERVER Variable Method : There is another way to get the IP Address by using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables. The variable in the $_SERVER array is created by the web server such as apache and those can be used in PHP.

What is the client's IP address?

Client IP addresses describe only the computer being used, not the user. If multiple users share the same computer, they will be indistinguishable. Many Internet service providers dynamically assign IP addresses to users when they log in.

How do I find my client IP address in cmd?

First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.


1 Answers

You can use IHttpContextAccessor:

private IHttpContextAccessor _accessor;
public Foo(IHttpContextAccessor accessor)
{
    _accessor = accessor;
}

Now you get IP address this way"

var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
like image 144
Sirwan Afifi Avatar answered Sep 27 '22 17:09

Sirwan Afifi