How do I get the caller's IP address in a WebMethod?

后端 未结 6 2117
慢半拍i
慢半拍i 2020-12-15 02:23

How do I get the caller\'s IP address in a WebMethod?

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


        
相关标签:
6条回答
  • 2020-12-15 03:05

    I made the following function:

    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";
            }
    }
    

    This work only in Intranet, if you have some Proxy or natting you should study if the original IP is moved somewhere else in the http packet.

    0 讨论(0)
  • 2020-12-15 03:09

    Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.

    0 讨论(0)
  • 2020-12-15 03:16

    HttpContext.Current.Request.UserHostAddress is what you want.

    0 讨论(0)
  • 2020-12-15 03:21

    Try this:

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

    Haven't tried it in a webMethod, but I use it in standard HttpRequests

    0 讨论(0)
  • 2020-12-15 03:21

    The HttpContext is actually available inside the WebService base class, so just use Context.Request (or HttpContext.Current which also points to the current context) to get access to the members provided by the HttpRequest.

    0 讨论(0)
  • 2020-12-15 03:22

    Try:

    Context.Request.UserHostAddress
    
    0 讨论(0)
提交回复
热议问题