Recipe 17.5. Resolving a Host Name or IP Address for Another Computer


Problem

You need to determine the host name for another computer from its IP address, or vice versa.

Solution

Sample code folder: Chapter 17\ResolveHostOrIP

The System.Net. Dns namespace includes methods that let you resolve an IP address to its matching host name or obtain an IP address for a host name.

Discussion

Create a new Windows Forms application, and add the following controls to Form1:

  • A TextBox control named IPAddress.

  • A Button control named FromIpToHost. Set its Text property to Show Host Name.

  • A TextBox control named HostName.

  • A Button control named FromHostToIp. Set its Text property to Show IP Address.

Add informational labels if desired. The form should look like the one in Figure 17-7.

Figure 17-7. Controls for the IP and host name resolution sample


Now add the following source code to the form's code template:

 Private Sub FromIpToHost_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles FromIpToHost.Click    ' ----- Convert from IP address to host name.    If (Trim(IPAddress.Text) <> "") Then _       MsgBox("Host Name" & vbCrLf & vbCrLf & _       Net.Dns.  GetHostEntry(IPAddress.Text).HostName) End Sub Private Sub FromHostToIp_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles FromHostToIp.Click    ' ----- Convert from host name to IP address.    Dim hostEntry As Net.IPHostEntry    Dim scanAddress As Net.IPAddress    Dim hostAddresses As String = ""    If (Trim(HostName.Text) <> "") Then       hostEntry = Net.Dns.GetHostEntry(HostName.Text)       For Each scanAddress In hostEntry.AddressList          hostAddresses &= vbCrLf & scanAddress.ToString()       Next scanAddress       If (hostAddresses = "") Then _          hostAddresses = vbCrLf & "None."       MsgBox("  IP Addresses" & vbCrLf & hostAddresses)    End If End Sub 

To use the program, enter an IP address in the IP Address field or a host name in the Host Name field, and click the applicable button to view the resolved name or address.

A bug in some versions of Windows XP prevents the GetHostEntry() method from working correctly. Specifically, if you supply an IP address of a remote system (out-side of your local network) to the method, the returned IPHostEntry.HostName property returns the IP address itself instead of the host name. This bug may be resolved in a Windows XP service pack or hotfix; it is resolved in Windows Vista.

See Also

Recipe 17.4 discusses finding the IP address(es) for the local workstation.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net