Obtain local IP in C # in UWP

5

How can you get the ip of the device in C #? That works in the field of UWP (Universal Windows Platform) known as universal applications of windows10

    
asked by Webserveis 05.01.2016 в 19:29
source

2 answers

5

You should ask about the internet connection profile, then check which is the current network adapter that matches the profile.

Keep in mind that you must validate many things, as if there are devices or not, or if there is more than one. The device can even exist but if you are not connected to a network. Etc.

Use this method to find the local IP that already has everything implemented.

    private string GetLocalIp()
    {
        var icp = NetworkInformation.GetInternetConnectionProfile();

        //sino hay disp de red devuelve null
        if (icp?.NetworkAdapter == null) return null;

        var hostname = (from hn in NetworkInformation.GetHostNames()
                       where hn.IPInformation?.NetworkAdapter != null
                          && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                          == icp.NetworkAdapter.NetworkAdapterId
                       select hn).First();


        return hostname?.CanonicalName;
    }

With this other method (below) you can find the address with which it goes to the internet, which is not the same local IP. NetworkInformation.GetHostNames() returns a list of interfaces some with IP, in any case the order of these interfaces is.

  • IP
    • Interfaces without IP
    • Interfaces with IP
  • Network type
    • External
    • Premises

so this method returns with the first interface with external IP.

    private string GetIp()
    {
        string ip = string.Empty;

        var ll = NetworkInformation.GetHostNames().ToList();

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

        return ip;
    }
    
answered by 05.01.2016 / 19:44
source
4

Here you can see API documentation: Windows.Networking

Try this code:

string ip;
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
    if (localHostName.IPInformation != null)
    {
        if (localHostName.Type == HostNameType.Ipv4)
        {
            ip = localHostName.ToString();
            break;
        }
    }
}
    
answered by 05.01.2016 в 19:53