How to obtain IP address of a client behind proxy via web service

 

Consider the following scenario:

One of my customers would like to know how to obtain IP address of a client with web service. The application at client side will call a web service method hosted on IIS server and that web service could get the IP address of the client then determine whether the IP address is valid to get accessed. His product environment has proxy server and the exact IP address he wants to obtain is the one used by router to access external network. Here, I would like to provide a general method to fetch clients’ IP address through web service and give an explanation on the result in terms of different hardware conditions.

[Sample Code]

===========

[WebMethod]

public string GetCustomerIP()

{

string CustomerIP = "";

if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)

{

          CustomerIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

}

else

{

           CustomerIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

 }

            return CustomerIP;

}

In above sample code, HTTP_VIA is used to judge whether the client is using proxy server. If client uses proxy server, then the web method will try to obtain IP address behind the proxy server. In many situations, the IP addresses we get are probably the addresses of proxy server. Below is the information on HTTP proxy:

1. Not Use Any Proxy Server:

REMOTE_ADDR = IP address of client

HTTP_VIA = No value or No display

HTTP_X_FORWARDED_FOR = No value or No display

2. Use Transparent Proxies:

REMOTE_ADDR = IP address of proxy server

HTTP_VIA = IP address of proxy server

HTTP_X_FORWARDED_FOR = Real IP address of client

3. Use Normal Anonymous Proxies:

REMOTE_ADDR = IP address of proxy server

HTTP_VIA = IP address of proxy server

HTTP_X_FORWARDED_FOR = IP address of proxy server

4. Use Distorting Proxies:

REMOTE_ADDR = IP address of proxy server

HTTP_VIA = IP address of proxy server

HTTP_X_FORWARDED_FOR = Random IP address

5. Use High Anonymity Proxies (Elite proxies):

REMOTE_ADDR = IP address of proxy server

HTTP_VIA = No value or No display

HTTP_X_FORWARDED_FOR = No value or No display

Another fact that may affect the result of above web service is the configuration of router. If the router of local area network enables NAT (network address translation), then the IP address obtained is the address used by the router to access external network. If NAT is disabled, then the IP address is the client's IP address within local area network.

Before use above sample code, we should first consider the real product environment and then use it accordingly.

Reference

========

A Probability to Get Wrong Information

https://www.codeproject.com/KB/cs/KBSoftIPLocator.aspx

Getting the Real IP Of Your Users

https://www.thepcspy.com/read/getting_the_real_ip_of_your_users

Best regards,

 

Hanson Wang