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

2019-04-25 07:34发布

问题:

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;
}

回答1:

You may try like this :

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 answer above is also right



回答2:

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



回答3:

based on answer by @John Zhang, but with fix to not throw LINQ error about multiple matches and return 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 the Ipv4 which is the default (implicit) parameter value to get the Ipv6 address



标签: c# ip uwp