繁体   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