Recipe 17.4. Get the Local Computer's IP AddressProblemYou want to determine the IP address of the computer on which your program is running. SolutionSample code folder: Chapter 17\LocalIPAddresses Use the features in the System.Net. Dns namespace to obtain the IP address(es) for the local host. A single workstation may have multiple IP addresses; this generally occurs when multiple networking cards are installed and active on that workstation. DiscussionIt may not be possible to determine the single IP address for your computer, because a computer may have multiple addresses. What .NET can give you is a list of all current IP addresses for the workstation, and its host name as well. The following code displays the local host name and all related IP addresses for that host. It uses the System.Net.Dns namespace, which includes features for managing IP addresses and related hosts: Dim hostAddresses() As Net.IPAddress Dim ipList As String = "" Dim oneAddress As Net.IPAddress hostAddresses = Net.Dns. GetHostAddresses( _ Net.Dns.GetHostName()) For Each oneAddress In hostAddresses ipList &= vbCrLf & oneAddress.ToString() Next oneAddress MsgBox("The IP address(es) for host '" & _ Net.Dns.GetHostName() & "' are:" & vbCrLf & ipList) On our system, this code displayed the message box in Figure 17-6. The GetHostAddresses() method returns IP addresses as they are understood by the local host. These addresses may differ from the IP address of that same workstation as viewed from the Internet. A router that implements Network Address Translation (NAT) can mask the actual (local) IP address of a system. Figure 17-6. Displaying the local host's IP addressSee AlsoRecipe 17.5 discusses determining IP addresses for systems other than the local workstation. |