Often we collect the users information visited to our site for audit or records for analysis and security.

We can get the value from ServerVariables collections of key “HTTP_X_FORWARDED_FOR” or “REMOTE_ADDR”.

Sometimes our visitors are using either a proxy server or a router and the standard Request.UserHostAddress only finds the IP address of the proxy server or router. When this is the case the user’s IP address is then stored in the server variable (“HTTP_X_FORWARDED_FOR”).

Therefore, we can first try with “HTTP_X_FORWARDED_FOR” and if that is empty we then simply check ServerVariables("REMOTE_ADDR").

Sample Code: C#

public string GetClientIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string clientIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(clientIPAddress))
    {
        string[] addresses = clientIPAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}

Lastly, we get IP and log the the value in to Database or log files.

Kind Regards

By Rijwan Ansari

Research and Technology Lead | Software Architect | Full Stack .NET Expert | Tech Blogger | Community Speaker | Trainer | YouTuber. Follow me @ https://rijsat.com Md Rijwan Ansari is a high performing and technology consultant with 10 plus years of Software Development and Business Applications implementation using .NET Technologies, SharePoint, Power Platform, Data, AI, Azure and cognitive services. He is also a Microsoft Certified Trainer, C# Corner MVP, Microsoft Certified Data Analyst Associate, Microsoft Certified Azure Data Scientist Associate, CSM, CSPO, MCTS, MCP, with 15+ Microsoft Certifications. He is a research and technology lead in Tech One Global as well as leading Facebook community Cloud Experts Group and SharePoint User Group Nepal. He is a active contributor and speaker in c-sharpcorner.com community, C# Corner MVP and his rank at 20 among 3+ millions members. Additionally, he is knee to learn new technologies, write articles, love to contribute to the open-source community. Visit his blog RIJSAT.COM for extensive articles, courses, news, videos and issues resolution specially for developer and data engineer.

Leave a Reply

Your email address will not be published. Required fields are marked *