Map between host names and IP addresses in C#

[IP addresses]

When you enter a host name and click Go, the program uses the following code to look up the host and display the IP addresses associated with it.

using System.Net;
...
// Display the entered host's IP address.
private void btnGo_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;
    lstAddresses.Items.Clear();
    txtHost.Clear();
    try
    {
        IPHostEntry ip_host_entry =
            Dns.GetHostEntry(txtHost.Text);
        foreach (IPAddress address in ip_host_entry.AddressList)
        {
            lstAddresses.Items.Add(address.ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    this.Cursor = Cursors.Default;
}

The code clears its ListBox and then uses the Dns.GetHostEntry method to get information about the host. It loops through the host information’s AddressList collection of IPAddress objects and adds the IP addresses to the ListBox.

When you select an entry in the ListBox, the following code displays the host assigned to the selected IP address.

// Look up the selected IP address's host.
private void lstAddresses_SelectedIndexChanged(
    object sender, EventArgs e)
{
    IPHostEntry ip_host_entry =
        Dns.GetHostEntry(lstAddresses.SelectedItem.ToString());
    txtRecoveredHost.Text = ip_host_entry.HostName;
}

This code uses the Dns.GetHostEntry method to get information about the selected IP address. It then displays the assigned host’s name.

Previously this program returned multiple IP addresses for a single host. For example, the loookup for maps.google.com might return a dozen or more IP addresses. The current program seems to return a single address. I suspect this is a change in Windows 10 but I’m not sure. If you have more information about this, please post it in a comment below.

If you look up the host localhost, the program lists the two special IP addresses ::1 and 127.0.0.1. If you click either of those in the ListBox, the program displays your computer’s name.

If you enter your computer’s name in the Host text box or if you leave it blank, the program seems to return your current IP address plus some IPv6 addresses. See WikiPedia for more information on IPv6 addresses. If you click one of those valeus in the ListBox, you should see the host name followed by a dot and the DNS domain name. For more information on this, see this WikiPedia entry.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in internet, network, system and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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