How to get your local machines IP address using C#

I’m working on this app that pulls the ip address from the request headers. When debugging the app locally the headers are always “127.0.0.1”, which doesn’t help because I need to know the actual IP address. Here is one way to get the local machines IP address, you can modify to return whatever IP Address type you need. In my case I need the IPv4 so I look for the address byte with a length of 4.


string netscalarHeader = "client-ip";
string ipAddress = (HttpContext.Current.Request.Headers[netscalarHeader] == null) ? HttpContext.Current.Request.UserHostAddress : HttpContext.Current.Request.Headers[netscalarHeader];
if (string.IsNullOrEmpty(ipAddress) || string.Compare("127.0.0.1", ipAddress) == 0)
{

 ipAddress = Array.Find<ipaddress>(Dns.GetHostEntry(Dns.GetHostName()).AddressList,
         new Predicate<ipaddress>(delegate(IPAddress s)
         {
          return s.GetAddressBytes().Length == 4;
         }</ipaddress></ipaddress>``)).ToString();
}