25 March 2007
How to get your local machines IP address
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(Dns.GetHostEntry(Dns.GetHostName()).AddressList,
new Predicate(delegate(IPAddress s)
{
return s.GetAddressBytes().Length == 4;
})).ToString();
}
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using
Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.