如何在WebMethod中获取呼叫者的IP地址?

时间:2008-09-24 22:31:36

标签: c# asp.net web-services

如何在WebMethod中获取呼叫者的IP地址?

[WebMethod]
public void Foo()
{
    // HttpRequest... ? - Not giving me any options through intellisense...
}

使用C#和ASP.NET

6 个答案:

答案 0 :(得分:84)

答案 1 :(得分:8)

请注意。 IP地址不能用于唯一标识客户端。 NAT防火墙和企业代理无处不在,并且将许多用户隐藏在单个IP之后。

答案 2 :(得分:6)

尝试:

Context.Request.UserHostAddress

答案 3 :(得分:4)

试试这个:

string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

没有在webMethod中尝试过,但我在标准的HttpRequests

中使用它

答案 4 :(得分:2)

HttpContext实际上在WebService基类中可用,所以只需使用Context.Request(或HttpContext.Current也指向当前上下文)来访问由HttpRequest基类提供的成员。 {{1}}。

答案 5 :(得分:0)

我做了以下功能:

static public string sGetIP()
{
    try
    {
        string functionReturnValue = null;

        String oRequestHttp =
            WebOperationContext.Current.IncomingRequest.Headers["User-Host-Address"];
        if (string.IsNullOrEmpty(oRequestHttp))
        {
            OperationContext context = OperationContext.Current;
            MessageProperties prop = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint =
                prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            oRequestHttp = endpoint.Address;
        }
        return functionReturnValue;
    }
    catch (Exception ex)
        {
            return "unknown IP";
        }
}

这项工作仅适用于Intranet,如果你有一些代理或natting,你应该研究原始IP是否被移动到http数据包的其他地方。

相关问题