Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get user IP in c#

Tags:

c#

I want to get the user IP and insert it in a table.I'm using tho following:

SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'1',@ip)", con);
cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("@raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("@ip", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);

But when I look in the table at the column Ip i only get 1...can you give me an explanation?

like image 575
user1147188 Avatar asked Dec 16 '22 04:12

user1147188


2 Answers

You could use:

string ipAddress = Request.UserHostAddress;
like image 161
Neil Knight Avatar answered Jan 08 '23 14:01

Neil Knight


Your program is likely running correctly. ::1 is the local IP address in IPv6. If you're running this on Windows Vista or later from your local machine then everything is working correctly.

This is a better way to grab a user's IP address though:

string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

If the user is behind a proxy of some type then you will get the proxy address rather than the end user's IP address. HTTP_X_FORWARDED_FOR will typically be the user's real IP address. If that's empty then you should at REMOTE_ADDR.

like image 26
Mark Avatar answered Jan 08 '23 13:01

Mark