I was working on a new pet project for Windows 10 IoT Core.
At this moment Win10 IoT Core is not supporting the Wi-pi Wi-Fi dongle. So I am using a Dlink 505 mobile companion to attach my Raspberry Pi b2 to my local network. This works great although Visual Studio has some trouble detecting the device.
But because the default app (yes, this is just an app) on the Pi shows the current IP-address, I can simply submit that address when deploying (in the project settings).
So far so good.
But when I deployed my own app I ran into a little problem. My Pi gets the current IP-address dynamically so at one point my deployment was not working anymore. The device had a new IP-address….
And this address is also needed for RDP so it is rather important.
I wanted to read the current IP address in C# code so I could show it in my own app. This seems a bit trivial, but Google was not helping me this time. All examples were based on System.Net so that was not working.
Then I was thinking, could it be that the default app is just open sourced? That way I could look in the code MSFT provided.
And yes it is! Just go to the github location.
And there I found the code to read the IP4 address (now a bit modified):
public static string GetCurrentIpv4Address() { var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp != null && icp.NetworkAdapter != null && icp.NetworkAdapter.NetworkAdapterId != null) { var name = icp.ProfileName; var hostnames = NetworkInformation.GetHostNames(); foreach (var hn in hostnames) { if (hn.IPInformation != null && hn.IPInformation.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId && hn.Type == HostNameType.Ipv4) { return hn.CanonicalName; } } } return "---"; }
Resolve the namespaces if needed…
So thank you MSFT for making the code available.