Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / C#
Tip/Trick

DNS resolving and Parsing IP Address in Metro Style Applications (WinRT)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
4 Mar 2013CPOL2 min read 26.2K   358   11   1
DNS resolving and parsing IP address in Metro Style applications (WinRT).

Introduction

DNS resolving, IP address comparisons, and getting IP information are basic tasks that we perform in applications that communicate with the network. For all those who have worked with previous .NET versions might get confused when they want to perform a DNS resolve or get IP information in Metro style application (WinRT) because the very familiar IP address class like shown below is Missing in Action.

C#
IPHostEntry ipHostInfo = Dns.GetHostEntry(Address);   
IPAddress ipAddress = ipHostInfo.AddressList[0];// IPAddress.Parse(address);
IPEndPoint endPoint = new IPEndPoint(ipAddress, Port); 

Instead a Hostname class has been introduced in WinRT.

Background

The HostName class is used to initialize and provide data for a hostname used in network apps. A HostName object can be used for a local hostname or a remote hostname used to establish a network connection. The HostName object is used by many classes in other related namespaces for network apps. These include the following:

Many classes in the Windows.Networking.Sockets namespace using sockets and WebSockets. The NetworkInformation class in the Windows.Networking.Connectivity namespace.

The below application is a simple tool which allows you to parse a string to IP address, resolve DNS, and also to compare different IP addresses. You can use the methods used here in your own applications. 

Image 1

Using the Code

Including the namespaces:

C#
using Windows.Networking;
using Windows.Networking.Connectivity;
using Windows.Networking.Sockets; 

In order to perform a DNS resolve, the below method can be used. This is an async method which will get the address as a string and will perform the DNS resolve and returns the IP address itself.

C#
public static async Task<string> ResolveDNS(string remoteHostName)
{
    if (string.IsNullOrEmpty(remoteHostName))
        return string.Empty;

    string ipAddress = string.Empty;

    try
    {
        IReadOnlyList<EndpointPair> data = 
          await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");

        if (data != null && data.Count > 0)
        {
            foreach (EndpointPair item in data)
            {
                if (item != null && item.RemoteHostName != null && 
                              item.RemoteHostName.Type == HostNameType.Ipv4)
                {
                    return item.RemoteHostName.CanonicalName;
                }
            }
        }
    }
    catch (Exception ex)
    {
        ipAddress = ex.Message; 
    }

    return ipAddress;
} 

Now to parse a string to a IP address (hostname), you can use the below method:

C#
public static bool GetHostName(string ipOrhost, out HostName hostName)
{
    HostName internalHostName = null;
    bool isValidHost = false;

    try
    {
        internalHostName = new HostName(ipOrhost);
        isValidHost = true;
    }
    catch (Exception ex)
    {
        isValidHost = false;
        internalHostName = null;
        // Exception Invalid Host name
    }
    finally
    {
        hostName = internalHostName;
    }
    return isValidHost;
}

To perform a IP address comparison, we can use the below method:

C#
public static async Task<bool> CompareIpAddress(string baseAddress, string secondAddress)
{
    bool isequal = false;

    if (string.IsNullOrWhiteSpace(baseAddress) || string.IsNullOrWhiteSpace(secondAddress))
        return isequal;

    string ipAddressBase = await ResolveDNS(baseAddress);
    string ipAddressSecond = await ResolveDNS(secondAddress);

    if (string.IsNullOrWhiteSpace(ipAddressBase) || string.IsNullOrWhiteSpace(ipAddressSecond))
        return isequal;

    if (ipAddressBase.Equals(ipAddressSecond))
        isequal = true;

    return isequal;
} 

The above methods have been called in the Click events to demonstrate the use of it.

C#
private async void btnResolve_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(txtDnsIP.Text))
    {
        try
        {
            lblResolveAddress.Text = await ResolveDNS(txtDnsIP.Text);
        }
        catch (Exception ex)
        {
            lblResolveAddress.Text = "Invalid";
        }
    }
}

private async void btnCompare_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(txtBaseAddress.Text) &&
        !string.IsNullOrEmpty(txtComAddress.Text))
    {
        try
        {
            bool result = await CompareIpAddress(txtBaseAddress.Text, txtComAddress.Text);

            if (result)
            {
                lblResullt2.Text = "Addresses are Same";
            }
            else
            {
                lblResullt2.Text = "Addresses Differ ";
            }
        }
        catch (Exception ex)
        {
            
        }
    }
}

private void btnShowInfo_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(txtUrl.Text))
    {
        try
        {
            HostName hostInfo = null;

            if (GetHostName(txtUrl.Text, out hostInfo))
            {
                if (hostInfo != null)
                {
                    StringBuilder info = new StringBuilder();
                    info.AppendLine(string.Format("CanonicalName - {0}", hostInfo.CanonicalName));
                    info.AppendLine(string.Format("DisplayName - {0}", hostInfo.DisplayName));
                    info.AppendLine(string.Format("RawName - {0}", hostInfo.RawName));
                    info.AppendLine(string.Format("Type - {0}", hostInfo.Type.ToString()));
                    lblResultInfo.Text = info.ToString();
                }
            }
            else
            {
                lblResultInfo.Text = "Error Hostname";

            }
        }
        catch (Exception ex)
        {

        }
    }
}

The HostName class has the below properties:

Image 2

Points of Interest

This is a Metro style application which requires .NET Framework 4.5 to work.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFailing if client in private network and dont have internet connection Pin
fahad.sust12-Nov-13 21:53
fahad.sust12-Nov-13 21:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.