There may be times when you need to know the IP address of your machine, such as when you're writing some networking code. This tip shows how you can figure out the IP address of your current computer using VB.NET's System.Net.Dns class.
This class offers a simple way of determining the IP address of a machine by utilizing its methods GetHostName and GetHostByName. The class also offers domain name resolution services. Its GetHostName method allows you to find out the host name of the current machine. You can use the GetHostByName method to determine the IP address of the machine.
I'll present two examples in which I achieve the same functionality in two slightly different ways, while the end result for both is exactly the same. (In the second example, I also utilize a Resolve method of the same class.)
In Listing A, I determine the host name of the current machine by utilizing the GetHostName method of the System.Net.Dns class. Then, I use this host name as a parameter necessary to determine the IP address of the current computer. For that I utilize the GetHostByName method of the same class and pass to it the host name of the machine. Since the GetHostByName method returns a list of usable IP addresses, I only pull information about the first item in the array by specifying AddressList(0) and then converting the whole expression to string. After that, I display both the host name and the IP address in a message box.
In Listing B, I determine the host name of the current machine and then use the Resolve method of the same class, passing to it the host name and pulling the information only about the first item in the Addresslist and converting the expression into a string. The result is displayed in a message box.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!