How to find local IP address in Win 10 UWP project

I am currently trying to connect an administrative console application to a Win 10 UWP application. I am having problems using System.Net.Dns from the following console code.

How can I get device IP addresses

Here is the console code of the application I'm trying to execute.

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; } 
+6
source share
3 answers

You can try the following:

 private string GetLocalIp() { var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp?.NetworkAdapter == null) return null; var hostname = NetworkInformation.GetHostNames() .SingleOrDefault( hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); // the ip address return hostname?.CanonicalName; } 

The above answer is also right.

+10
source

Use this to get the iPaddress of a host in a UWP application, I tested it:

  foreach (HostName localHostName in NetworkInformation.GetHostNames()) { if (localHostName.IPInformation != null) { if (localHostName.Type == HostNameType.Ipv4) { textblock.Text = localHostName.ToString(); break; } } } 

And look at the Doc API here

+12
source

based on @John Zhang's answer, but with a fix, don't throw a LINQ error about multiple matches and return an IPv4 address:

  public static string GetLocalIp(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 Ipv4, which is the default (implicit) to get the IPv6 address

+4
source

All Articles