Get Local IP address in ASP.NET

Niladri.Biswas
Posted by Niladri.Biswas under ASP.NET category on | Points: 40 | Views : 3354
Approach 1:

public string GetLocalIPAddress()
{
string strIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(strIP))
{
string[] ipRange = strIP.Split(',');
strIP = ipRange[0];
}
else
{
strIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return strIP;
}


Approach 2:
private string GetLocalIPAddress()
{
string strHostName = string.Empty;
string localIP = "127.0.0.1"; //set a default value
strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;

foreach (IPAddress ip in addr)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}


Hope this will be helpful

Comments or Responses

Login to post response