We help IT Professionals succeed at work.

How to get the client ip when web server is behind a NAT?

kazadome
kazadome used Ask the Experts™
on
Dear All:
I have one IIS 6.0 web server on Windows Server 2003.  There is one simple page(x.aspx) in the web server, and one major function of the page is "show the client ip in the page content".  The question is the server is behind a NAT.  When I use the code below, the NAT's ip always shown instead.  Is there any method to get the real client IP in this web server.  Thanks for your reading.
// First method
Request.UserHostAddress = NAT's IP
 
// Second method
Request.ServerVariables["REMOTE_ADDR"].ToString() = NAT's IP
 
// Third method
Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() = NAT's IP

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
I don't think so.
You could try 'HTTP_X_FORWARDED_FOR'
http://www.dreamincode.net/code/snippet1745.htm

Author

Commented:
Thanks for your reply.
I modified my code below, and got the result is ...
--------------
Request.UserHostAddress: NAT's real IP
Request.UserHostName: NAT's real IP
REMOTE_ADDR: NAT's real IP
HTTP_VIA: 1.1 xxx.xxx.com.tw (Access Gateway 3.0.4-60)
HTTP_X_FORWARDED_FOR: NULL
---------------
string mm = String.Empty;
mm += "Request.UserHostAddress: " + Request.UserHostAddress + "\r\n";
mm += "Request.UserHostName: " + Request.UserHostName + "\r\n";
mm += "REMOTE_ADDR: " + Request.ServerVariables["REMOTE_ADDR"].ToString() + "\r\n";
 
if (Request.ServerVariables["HTTP_VIA"] != null)
  mm += "HTTP_VIA: " + Request.ServerVariables["HTTP_VIA"].ToString() + "\r\n";
else
  mm += "HTTP_VIA: " + "NULL" + "\r\n";
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  mm += "HTTP_X_FORWARDED_FOR: " + Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString() + "\r\n";
else
  mm += "HTTP_X_FORWARDED_FOR: " + "NULL" + "\r\n";
 
TextBox1.Text = mm;

Open in new window

Top Expert 2007
Commented:
Unless your NAT device has the capability of adding a custom HTTP header on HTTP requests containing the clients IP address there is no way to do what you are trying to do.

Sorry.

Dave Dietz

Author

Commented:
Thanks for your comments.  I give up!!