How to get your local machines IP address using C#
1 min read
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();} Share:
Share on LinkedIn
Quick Share: Your custom post text has been copied to your clipboard! Click the button below to open LinkedIn's share dialog, then paste it.
💡 Tip: LinkedIn will open in a new tab. Use Ctrl+V (or Cmd+V on Mac) to paste your text.
Note: LinkedIn will show the article preview. You can add your custom text above it.