I am currently trying to port an administrative console application over to a Win 10 UWP app. I am having trouble with using the System.Net.Dns from the following console code.
How can I get the devices IP
Here is the console app code that I am trying to port over.
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Use this to get host IPaddress in a UWP app, I've tested it:
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
textblock.Text = localHostName.ToString();
break;
}
}
}
And see the API Doc here
based on answer by @John Zhang, but with fix to not throw LINQ error about multiple matches and return Ipv4 address:
public static string GetFirstLocalIp(HostNameType hostNameType = HostNameType.Ipv4)
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.FirstOrDefault(
hn =>
hn.Type == hostNameType &&
hn.IPInformation?.NetworkAdapter != null &&
hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);
// the ip address
return hostname?.CanonicalName;
}
obviously you can pass HostNameType.Ipv6 instead of the Ipv4 which is the default (implicit) parameter value to get the Ipv6 address
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With