Resolving an IP address from a Host Name and vice versa

Posted by: Suprotim Agarwal , on 1/18/2008, in Category WinForms & WinRT
Views: 49049
Abstract: In this article, we will use the System.Net namespace to find out the IP address by passing the host name. We will also use the IP address to find the host name. We will be using the System.Net.Dns class which can be used to retrieve information about a host.
Resolving an IP address from a Host Name and vice versa
 
In this article, we will use the System.Net namespace to find out the IP address by passing the host name. We will also use the IP address to find the host name. We will be using the System.Net.Dns class which can be used to retrieve information about a host.
DNS stands for Domain Name System. In simple words, a domain name is a meaningful name that identifies an internet address. DNS is a system where these domain names are located.
 
Retrieve IP address from Host Name
 
The Dns class in the System.Net namespace is a static class that provides domain name resolution functionality. The Dns.GetHostEntry() contains 2 overloads for accepting either a hostname or an IP address and returns an instance of IPHostEntry. The IPHostEntry is a helper class that can associate multiple IP addresses with the host name.
 
Let us see how to resolve IP addresses from a host name.
 
Step 1: Create a windows project. In the Form1.cs, add the System.Net namespace
 
C#
using System.Net;
 
VB.NET
Imports System.Net
 
Step 2: Add a Textbox (txtIP), Button control (btnIP) and a Listbox (lstIP) to the form.
 
Step 3: In the button click event of btnIP, type the following code:
 
C#
private void btnIP_Click(object sender, EventArgs e)
        {
            lstIP.Items.Clear();
            try
            {
                // Host Name resolution to IP
                IPHostEntry host = Dns.GetHostEntry(txtIP.Text.Trim());
                IPAddress[] ipaddr = host.AddressList;
                // Loop through the IP Address array and add the IP address to Listbox
                foreach (IPAddress addr in ipaddr)
                {
                    lstIP.Items.Add(addr.ToString());
                }
            }
            // Catch unknown host names
            catch (System.Net.Sockets.SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch(System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
 
        }
 
VB.NET
Private Sub btnIP_Click(ByVal sender As Object, ByVal e As EventArgs)
                  lstIP.Items.Clear()
                  Try
                        ' Host Name resolution to IP
                        Dim host As IPHostEntry = Dns.GetHostEntry(txtIP.Text.Trim())
                        Dim ipaddr As IPAddress() = host.AddressList
                        ' Loop through the IP Address array and add the IP address to Listbox
                        For Each addr As IPAddress In ipaddr
                              lstIP.Items.Add(addr.ToString())
                        Next addr
                  ' Catch unknown host names
                  Catch ex As System.Net.Sockets.SocketException
                        MessageBox.Show(ex.Message)
                  Catch ex As System.Exception
                        MessageBox.Show(ex.Message)
                  End Try
 
End Sub
 
Just enter a hostname, say www.dotnetcurry.com and click the button. You will see the I.P addresses displayed in the list box.
 
Retrieve Host Name from IP Address
Step 1: Add a Textbox(txtHost), Button(btnHost) and a Label(lblHost) to the form.
Step 2: In the btnHost click, use the following code
C#
private void btnHost_Click(object sender, EventArgs e)
        {
            IPHostEntry host = Dns.GetHostEntry(txtHost.Text.Trim());
            lblHost.Text = host.HostName;
        }
VB.NET
Private Sub btnHost_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim host As IPHostEntry = Dns.GetHostEntry(txtHost.Text.Trim())
      lblHost.Text = host.HostName
End Sub
 
Type “127.0.0.1” in textbox and click the button to see the hostname.
That was quiet easy. You saw how easy it was to use the System.Net.Dns class to resolve DNS names and IP addresses. If the hostname does not resolve in case of an invalid entry, a Socket exception is thrown back to the user.
I hope this article was useful and I thank you for viewing it.
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by giteshjoshi on Monday, January 21, 2008 2:06 AM
Hi Suprotim,
           Very Nice article specially when you need to do so. I want to add some code, so as if the user wants to know his own system IP Address then...... Here it goes.....

//Add this Namespace.
using System.Net;

namespace HostName
{
  class HostNameClass
  {
     public string GetHostName()
        {
            string hostname = "";
            try
            {
               IPHostEntry host = Dns.GetHostEntry((Dns.GetHostName()).ToString());
                hostname= host.AddressList[0].ToString(); //This will give you your system IP address.
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message.ToString());
            }
            return hostname;
        }//Ending method GetHostName()

        static void Main(string[] args)
        {
            HostNameClass obj = new HostNameClass();
            string hostName = obj.GetHostName();
            Console.Write(hostName);
            Console.Read();
        }
        
  }
}


Hope this code must be helpful for the readers.

Thanks and Regards,
Gitesh
Comment posted by ganesh on Friday, January 25, 2008 11:54 AM
Really nice and cool article......

Thanks..
Comment posted by anubhava on Monday, March 10, 2008 12:36 AM
Hi,
I want to know that How can i resolve Proxy Server Name by vb.net.

Thanks
Anubhava dimri
9250168195
Comment posted by Pgmer on Saturday, July 19, 2008 7:35 AM
To get weather The web address is correct or not code goes like this.
  Dim WebResponse As HttpWebResponse = Nothing
        Try
            Dim WebRequest As HttpWebRequest = HttpWebRequest.Create(url)
            WebResponse = DirectCast(WebRequest.GetResponse(), HttpWebResponse)
            Return True
        Catch
            Return False
        Finally
            If WebResponse IsNot Nothing Then WebResponse.Close()
        End Try
Comment posted by Murugan Andezuthu Dharmaratnam on Sunday, August 30, 2009 9:57 AM
ASP .NET domain name to ip resolution, Get IP Address Given Host Name

Here's the 3 Line code to get IP From Host Name

Dim IPAddress() As System.Net.IPAddress
IPAddress = System.Net.Dns.GetHostAddresses("smtp.mail.yahoo.com")
Dim oSmtpClient As New SmtpClient
oSmtpClient.Host = IPAddress(0).ToString

<a href="http://muruganad.com/ASP.NET/ASP_.NET_domain_name_to_ip_resolution_Get_IP_Address_Given_Host_Name.html">http://muruganad.com/ASP.NET/ASP_.NET_domain_name_to_ip_resolution_Get_IP_Address_Given_Host_Name.html</a>

Thanks!
  <a href-"http://muruganad.com">Murugan Andezuthu Dharmaratnam</a>
Comment posted by Rajeev on Wednesday, October 14, 2009 2:13 AM
How about resolving IP Address of External Domain e.g. www.microsoft.com when all you Internet Traffic routes through a Proxy Server
Comment posted by Matt on Friday, November 13, 2009 11:31 AM
If I specify an invalid IP with this code it doesn't throw an error.  It just returns the IP address I specified.  Any idea why?
Comment posted by mukesh on Saturday, April 7, 2012 3:33 AM
hi sir my proble is ---
my need is my data save in online in vb.net desktop applcation form .please give ne solution .


thnkas
Comment posted by Vikram on Sunday, March 17, 2013 6:19 PM
I've to perform the same for a SharePoint 2010 application.. user enters DNS name and that particular DNS IP address should be retrived.. please suggest how to perform the same.
Comment posted by William Simukoko on Tuesday, July 2, 2013 1:46 PM
To get an IP address for a hostmane. try this;

Dim inetServer As Array
        inetServer = System.Net.Dns.GetHostAddresses("my.host.name").ToArray

dim myipaddress=inetServer.GetValue(0)

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook