得到远程主机的IP地址 [英] Get the IP address of the remote host

查看:132
本文介绍了得到远程主机的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET有一个 System.Web.Htt prequest 类,它包含 ServerVariables 财产可以为我们提供从 REMOTE_ADDR 属性值的IP地址。

In ASP.NET there is a System.Web.HttpRequest class, which contains ServerVariables property which can provide us the IP address from REMOTE_ADDR property value.

不过,我无法找到一个类似的方式来获得的ASP.NET Web API的远程主机的IP地址。

However, I could not find a similar way to get the IP address of the remote host from ASP.NET Web API.

我怎样才能得到所发出请求的远程主机的IP地址?

How can I get the IP address of the remote host that is making the request?

推荐答案

这是可能做到这一点,但不是很发现 - 你需要使用属性包从传入的请求,并且需要访问属性取决于是否您正在使用IIS下的Web API(webhosted)或自托管。在code以下显示了如何可以做到这一点。

It's possible to do that, but not very discoverable - you need to use the property bag from the incoming request, and the property you need to access depends on whether you're using the Web API under IIS (webhosted) or self-hosted. The code below shows how this can be done.

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }

    if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }

    return null;
}

这篇关于得到远程主机的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆