RonC
RonC

Reputation: 33771

In Asp.Net Core core how to I get the web site's IP address?

In web forms if I needed to obtain the website server's IP address (say for logging) I could obtain it from request.ServerVariables["LOCAL_ADDR"]

How can it be obtain in Asp.Net Core when running in Kestral behind IIS or IIS Express?

Upvotes: 10

Views: 16778

Answers (4)

Bogdan
Bogdan

Reputation: 1393

This works for any type of apps asp.net or console only

Dns.GetHostEntry(Dns.GetHostName()).AddressList

or

from if in NetworkInterface.GetAllNetworkInterfaces()
where if.OperationalStatus == OperationalStatus.Up
from address in if.GetIPProperties().UnicastAddresses
select address

Upvotes: 2

user1095959
user1095959

Reputation: 1

You can also use IHttpContextAccessor class in .net core to get client's ip address

I found solution at this url How to get client ip address in .net core 2.x, is simple small code which gives ip address.

Upvotes: 0

Post Impatica
Post Impatica

Reputation: 16383

This is what worked for me using .net core 2.1

Adjust the regex to your needs. My prod web servers are in the 10.168.x.x range. my dev machine is in the 10.60.x.x range.

if(String.IsNullOrEmpty(localIpAddress))
{
    var ips = await System.Net.Dns.GetHostAddressesAsync(System.Net.Dns.GetHostName());

    string rgx = (env.IsDevelopment()) ? @"10{1}\.60{1}\..*" : @"10{1}\.168{1}\..*";
    var result = ips.FirstOrDefault(x => {
        Match m2 = Regex.Match(x.ToString(), rgx);
        return m2.Captures.Count >= 1;
    });
    localIpAddress = result.ToString();
}

Although in the end I ended up just using System.Net.Dns.GetHostName() because I didn't really need the IP address.

Upvotes: 7

tmg
tmg

Reputation: 20383

You can use HttpContext.Features.Get<IHttpConnectionFeature>() - docs:

var httpConnectionFeature = httpContext.Features.Get<IHttpConnectionFeature>();
var localIpAddress = httpConnectionFeature?.LocalIpAddress;

Upvotes: 13

Related Questions