views:

168

answers:

2

Hi all,

One of my functions in a class is called GetIpAddress() which returns the following string: System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]

This all works well in regular page loads and gets my ip address, but when i for example let a user place a comment, then the ip address is lost after postback and i get an empty string returned.

Am I missing something here maybe?

Kind regards, Mark

A: 

Do you have it wrapped in something like this?

if (!Page.IsPostBack) {
    GetIpAddress()
}

You need to either call the function every time, or store it in a Shared variable.

Another option (As @Marc mentioned) would be to simply call Request.UserHostAddress instead of GetIpAddress... it's almost the same amount of typing, but you don't have to have a custom function for it.

rockinthesixstring
+1  A: 

Use these ones:

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // a user is going through a proxy server

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Request.UserHostAddress;

Some explanation: REMOTE_ADDR The IP address of the remote host making the request.

REMOTE_HOST The name of the host making the request. If the server does not have this information, it will set REMOTE_ADDR and leave this empty.

igor