Recipe 17.4. Get the Local Computer s IP Address


Recipe 17.4. Get the Local Computer's IP Address

Problem

You want to determine the IP address of the computer on which your program is running.

Solution

Sample 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.

Discussion

It 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 address


See Also

Recipe 17.5 discusses determining IP addresses for systems other than 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