Getting local IP address programmatically in Windows 7

Getting local IP address programmatically in Windows 7

I created a small client app for my company that required the local IP address (assigned by DHCP) to determine what site it was on. It reads the second octet value, which is consistent with each of our buildings in our enterprise. From here, I can determine what content to load so no matter where the PC is placed, it automatically grabs content only specific to that location.

Anyway, when testing this application on Windows 7 it doesn’t load any content. Initial troubleshooting indicates the IP address is not resolving as it would on a Windows XP machine. I dug into the code today and noticed when run on Windows 7 the IP Address was coming up something like this:


This was achieved by using System.Net and the following C# code:

string hostname = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(hostname);
IPAddress[] ip = ipEntry.AddressList;

Then ip[0].ToString() will give you the IP Address, or in Windows 7 case, the IPv6 address you see above. Let me show you what worked for me:

First, make sure you’re referencing the System.Linq namespace in addition to System.Net. No, I’m not a Linq user or a fan, but it works, so I used it.

Next, replace the above code with the following:

string hostname = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(hostname);
string ip = ipEntry.AddressList.FirstOrDefault().ToString();

Note that Dns.GetHostByName is obsolete, and eventually will be replaced. However, the recommended “GetHostEntry” failed to return the IPv4 address I needed, but instead returned the IPv6 address mentioned above. I welcome feedback on what I might be doing wrong or how to improve on this process, but for now this solves my Windows 7 IP Address issue. Hope this helps someone else.

UPDATE: Thanks to the anonymous comment left that clarified my unfamiliarity with IPv6 address syntax. Corrections were made accordingly.

Comments are closed.
%d bloggers like this: