簡體   English   中英

如何在 ASP.NET Core MVC 中獲取本地設備 IP

[英]How to get local device IP in ASP.NET Core MVC

我正在開發一個 ASP.NET 核心項目,我有一個登錄表單,我想識別用戶嘗試登錄的設備。 這是我找到的,也是我用來獲取 IP 的:

userLogin.stringIP=Request.HttpContext.Connection.RemoteIpAddress.ToString();

有了這個,我只得到本地網關 IP 而不是設備的本地 IP。

更新

The example code works ,but when I publish the Website on my IIS Server it gives me the IP of IIS server, instead of device from where I try to acces the Website For example when I open the Website that is published on IIS server it gaves我是 IIS 服務器的 IP。我需要設備 IP 地址,我嘗試從中訪問網站。

如何獲得設備的本地 IP 的任何想法/建議。

提前致謝!

嘗試以下任何一種:

 var ip1 = Request.HttpContext.Connection.LocalIpAddress.ToString();
 var ip2 = Request.HttpContext.Connection.RemoteIpAddress.ToString();
 var ip3 = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
 var ip4 = HttpContext.Features.Get<IHttpConnectionFeature>()?.LocalIpAddress.ToString();

 string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
 if (Request.Headers.ContainsKey("X-Forwarded-For"))
     remoteIpAddress = Request.Headers["X-Forwarded-For"];

以下代碼將返回本地 IP 地址:

publicl static string GetLocalIpAddress()  
{  
    UnicastIPAddressInformation mostSuitableIp = null;  
    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();  
    foreach (var network in networkInterfaces)  
    {  
        if (network.OperationalStatus != OperationalStatus.Up)  
            continue;  
  
        var properties = network.GetIPProperties();  
        if (properties.GatewayAddresses.Count == 0)  
            continue;  
  
        foreach (var address in properties.UnicastAddresses)  
        {  
            if (address.Address.AddressFamily != AddressFamily.InterNetwork)  
                continue;  
  
            if (IPAddress.IsLoopback(address.Address))  
                continue;  
  
            if (!address.IsDnsEligible)  
            {  
                if (mostSuitableIp == null)  
                    mostSuitableIp = address;  
                continue;  
            }  
  
            // The best IP is the IP got from DHCP server  
            if (address.PrefixOrigin != PrefixOrigin.Dhcp)  
            {  
                if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)  
                    mostSuitableIp = address;  
                continue;  
            }  
            return address.Address.ToString();  
        }  
    }  
    return mostSuitableIp != null  
        ? mostSuitableIp.Address.ToString()  
        : "";  
}

如果 asp.net 核心項目位於用戶登錄的本地設備的防火牆之外,並且用戶正在使用私有 IP 地址(RFC 1918),那么他/她的本地地址防火牆將去除私有 ZA12A3079E1490B246將面向公眾的 IP 地址作為源 IP 地址。

您是否嘗試過Get local IP address中 mrchief 提供的解決方案?

他(她?)使用 Dns.GetHostEntry(Dns.GetHostName()) 獲取機器的本地 IP 地址。

值得嘗試。

問候 N

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM