i have a website and I want to store ip address and location of the users who are visiting my website. I tried many ways but the code below gives me the ip of server where my website is hosted and not client's ip.
//First code I tried.
bool GetLan = false;
string visitorIPAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan)
{
if (string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
}
var zaz = "";
zaz = visitorIPAddress.ToString();
//second code i tried
string VisitorsIPAddr = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = System.Web.HttpContext.Current.Request.UserHostAddress;
}
HttpContext.Current.Request or HttpContext.Request will contain the client's IP address - you don't need the above boilerplate code.
Try using the HttpRequest.UserHostAddress property in .NET Framework:
public ActionResult Test()
{
string clientIp = HttpContext.Current.Request.UserHostAddress;
...
}
Do note however that if there have been proxy servers between the client & your server, the IP may not be the client's IP but the proxy server's IP.
In these cases, you may find the original client IP in the X-Forwarded-For header but there are no guarantees for the presence of this header nor you being aware of the client's real IP in general.