ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. C #
  3. IP Address in C#?

IP Address in C#?

This article describes how to get user IP address using C#? or C# code to determine a visitor’s IP address. Summary of the article:
  • What is IP Address?
  • C# Code to Get Visitor/Client IP Address
  • Function to Get IP Address
What is IP Address?
IP address or internet protocol address is a unique identifying numerical number assigned to every single device (computer, printer) on the computer network that uses the Internet Protocol for communication. Like phone or car number IP address is used for identification. Any machine connected to the internet has an IP address. IP addresses have two common formats:
  1. IP Version 4 – example 192.168.100.250
  2. IP Version 6 – example 23CA:D3:0:1F3B:2AA: BF:FE28:9C5B
C# Code to Get Visitor/Client IP Address
Sometimes we need to get the IP address of the client machine. We collect this IP address for several purposes like: security purposes, to identify the visitors, during login times etc.
By using the following C# code we can get the IP address:
string IPAddress = string.Empty;
IPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
The server variable HTTP_X_FORWARDED_FOR returns the real IP address of a person
The server variable REMOTE_ADDR returns the IP address of the proxy or router.If the person is behind a proxy or router.
Function to Get IP Address
A sample C# function to obtain the IP address:
public string GetIPAddress()
{
    string IPAddress = string.Empty;
    IPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (IPAddress == null || IPAddress == "")
    {
        IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }
    return IPAddress;
}
In this way we can collect the Clint IP address in C#.

No comments