ProblemYou need to determine the host name for another computer from its IP address, or vice versa. SolutionSample 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. DiscussionCreate a new Windows Forms application, and add the following controls to Form1:
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 sampleNow 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 AlsoRecipe 17.4 discusses finding the IP address(es) for the local workstation. |