4

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?

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
user1147188
  • 135
  • 2
  • 3
  • 12
  • possible duplicate of [client ip address](http://stackoverflow.com/questions/3003242/client-ip-address) –  Jan 30 '12 at 09:05
  • Windows Forms? WCF? WebForms? ... what? – balexandre Jan 30 '12 at 09:06
  • 3
    You have IPv6 installed, and accesssing the web server locally from same machine, so the address comes out as `::1`?.. – GSerg Jan 30 '12 at 09:06
  • Is your problem with getting IP or saving? Print it to console – Bojan Kogoj Jan 30 '12 at 09:07
  • Are you sure IP is the last (out of 5 ) columns in the table? You might want to specify the column names explicitly. – devzero Jan 30 '12 at 09:07
  • Note to closers: This is not a duplicate of http://stackoverflow.com/questions/3003242/client-ip-address. Rather, it is a duplicate of http://stackoverflow.com/questions/1932843/iis-request-userhostaddress-returning-ipv6-1-even-when-ipv6-disabled – GSerg Jan 30 '12 at 09:09
  • the ip is saved in the table as ::1 – user1147188 Jan 30 '12 at 09:11
  • @GSerg did a close-request on the initial question - when there was no hint for "::1" - but you can do a close-request with this other question! –  Jan 30 '12 at 09:46

2 Answers2

7

You could use:

string ipAddress = Request.UserHostAddress;
Neil Knight
  • 47,437
  • 25
  • 129
  • 188
6

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.

Mark
  • 21,067
  • 14
  • 53
  • 71