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

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

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

using C# and ASP.NET

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.

Method 3

Try:

Context.Request.UserHostAddress

Method 4

Try this:

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

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

Method 5

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.

Method 6

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x