Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the local IP address on a Win 10 UWP project

Tags:

c#

ip

uwp

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;
}
like image 848
Daniel Jerome Avatar asked Nov 18 '15 01:11

Daniel Jerome


2 Answers

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

like image 166
panda Avatar answered Nov 15 '22 14:11

panda


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

like image 23
George Birbilis Avatar answered Nov 15 '22 14:11

George Birbilis