Get the network machine name in a Windows Store app

When developing Windows Store apps that support receiving push notifications, besides getting the application ID and hardware ID, I also like to get other useful information about the machine/device that can ease the management of the push notifications service. The network machine name is one of these useful information.

The class NetworkInformation that is in the namespace Windows.Networking.Connectivity has a method called GetHostNames, which returns a list of names associated with the machine (which may or may not belong to a domain), including the network machine name.

The names returned by the method GetHostNames can be one of four different types: DomainName, Ipv4, Ipv6, e Bluetooth.

Thus, we just need to iterate over the list of names returned by that method, and get the first entry of the type DomainName, if any.

For applications built with XAML/C# it would be something like this:

public string GetHostName()
{
    var hostNamesList = Windows.Networking.Connectivity.NetworkInformation
        .GetHostNames();

    foreach (var entry in hostNamesList)
    {
        if (entry.Type == Windows.Networking.HostNameType.DomainName)
        {
            return entry.CanonicalName;
        }
    }

    return null;
}

And for applications built with HTML/JavaScript, it would be something very similar:

function getHostName() {
    var hostNamesList = Windows.Networking.Connectivity.NetworkInformation
        .getHostNames();

    for (var i = 0; i < hostNamesList.length; i++) {
        var entry = hostNamesList[i];

        if (entry.type === Windows.Networking.HostNameType.domainName) {
            return entry.canonicalName;
        }
    }

    return null;
}
This entry was posted in .NET, JavaScript, Windows 8 and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>