Make editing your system's HOSTS file easy and safe

\[Editor's Note: VB Solutions is about using Visual Basic (VB) to build a variety of solutions to specific business problems. This column doesn't teach you how to write VB, but how to use VB as a tool to provide quick, easy-to-implement solutions that you can use right away.\]

Windows NT uses either a Domain Name System (DNS) server or a HOSTS file to let TCP/IP applications reference other systems in your network via meaningful names, instead of hard-to-remember numeric IP addresses. If a network has a DNS server, NT uses it rather than the HOSTS file for TCP/IP name resolution. However, many smaller networks don't have a DNS server and must rely on the HOSTS file to resolve TCP/IP host names to their IP addresses.

The HOSTS file is a standard text file that you can edit using a text editor such as Notepad. Although this method works, editing the HOSTS file with a text editor has some serious limitations. First, the HOSTS file has some subtle but important formatting rules that standard text editors don't enforce. Second, the IP addresses and TCP/IP host names that you enter in the HOSTS file must be correct; a standard text editor has no mechanism to ensure that you enter valid values. This month's VB Solutions utility, HOSTS File Edit, makes editing the HOSTS file a less error-prone process because it correctly formats the HOSTS file and lets you verify host names and IP addresses.

The Utility
Screen 1, page 206, shows the HOSTS File Edit utility's main editing window. When you start HOSTS File Edit, the utility automatically displays the contents of the HOSTS file in this window. Unlike a standard ASCII text editor, HOSTS File Edit doesn't let you directly type over the HOSTS file lines. Instead, you right-click the line you want to modify, and the program displays the pop-up menu you see in Screen 1. The menu options let you insert a new line; edit an existing line; or cut, copy, paste, or delete a line. If you right-click a line with an active IP address and host name, you also get the option to ping the remote host.

To add a new entry to the HOSTS file, you right-click the place where you want to insert the line and then select the menu's Insert option to display the Edit HOSTS File Entry dialog box shown in Screen 2, page 206. The utility formats the IP address, host name, and optional comment that you enter in this dialog box. (You must enter the IP address in the standard format.) Clicking OK inserts the new entry in the HOSTS file and closes the dialog box; clicking Cancel discards the new entry and closes the dialog box. When the utility writes the TCP/IP host entry line to the HOSTS file, it places the entry in the first position, which most TCP/IP applications that use the HOSTS file require. If you click Ping, the utility pings the remote host name you entered and verifies that the IP address is correct. (Clicking Ping is optional; thus, you can enter systems into the HOSTS file regardless of whether you are connected to them.) Screen 3, page 206, shows the Ping Host verification screen that displays when you click Ping. If the ping is not successful, the utility displays a warning message.

Inside the HOSTS File Edit Utility
Let's examine how to build the HOSTS File Edit utility. One of the key ways in which the utility differs from a standard text editor is that the utility lets you ping remote hosts and verify the host name and IP address. HOSTS File Edit implements this ping capability using ping32.dll, a DLL based on the ping.c sample that Microsoft distributes in its Winsock development sample. (For details about ping32.dll, see VB Solutions: "Building an Automated Mass Ping Utility," November 1997.) Ping32.dll contains one function (ping) declared in the ping.bas file. The VB declaration for the ping function follows:

Declare Function ping _

Lib "ping32.dll" _

(ByVal sHostName$, _

ByVal sIPAddr$, _

ByVal iDataLen%, _

lPingTime&, _

ByVal iTimeout%, _

ByVal iVerbose%) As Integer

The first parameter of the ping function is a string containing either the name or the IP address of the system to be pinged. The second parameter is a string that the ping function returns. This string contains the IP address of the pinged system. This parameter lets the calling program retrieve the IP address for a given TCP/IP host name. The third parameter specifies the size of the data packet sent with the ping. The maximum data length that ping32.dll allows is 1024 bytes. The fourth parameter, a long variable, returns the elapsed milliseconds the ping function required to execute. The fifth parameter contains the maximum time in milliseconds that the ping function waits for a response for sent or received packets. The sixth parameter specifies the mode of operation for the ping function. If you set this parameter to True, ping32.dll runs in verbose mode, the mode that displays all ping results and errors in a message box. Setting the sixth parameter to False runs ping32.dll in silent mode, the mode that reports any ping results and errors in the ping function's return code and output parameters. (You can download ping32.dll, its source code, and the code for the HOSTS File Edit utility from the Windows NT Magazine Web site at

When HOSTS File Edit starts, it executes the Form_Load subroutine in Listing 1. At callout A in Listing 1, you can see where the GetSystem32Dir function returns a string containing the path of the NT system directory, \winnt\system32. The GetSystem32Dir function uses the Win32 GetSystemDirectoryA API to dynamically retrieve the directory's path. The code at A appends the HOSTS file path to the system directory path and assigns this result to the sHostsFilePath string variable.

At B in Listing 1, the Open function opens the HOSTS file for input. Form_ Load uses the Line Input function to read each line of the HOSTS file and move the contents into the sTextLine variable. The AddItem method adds each line to the List_HOSTS list box. When Form_Load has read all the lines in the HOST file, the Close function closes the file and displays the HOSTS File Edit utility's main window (Screen 1).

As I mentioned previously, to edit the HOSTS file, you right-click in the HOSTS file list and select an option from the pop-up menu. Unfortunately, handling right-clicks in a list box isn't quite as easy in VB as handling left-clicks. To display the pop-up menu after the right-click, I use the MouseDown function of the List_HOSTS list box control. Listing 2 shows the List_HOSTS_MouseDown subroutine.

After declaring the working variables and enabling VB's error handler, List_HOSTS_MouseDown checks whether the user right-clicked the mouse button. If a right-click activated the subroutine, List_HOSTS_MouseDown sets the List_HOSTS.ListIndex property to the line the user clicked. You determine this line by dividing the height coordinate of the mouse pointer (Y) by the result of the height of the list box divided by 22 (the number of lines the list box displays).

At A in Listing 2, the subroutine checks the first character of the line to determine whether it's a numeric value. If the first character is numeric, the user has clicked a line that contains a host entry (a host entry must always begin in the first position of the HOSTS file). Otherwise, the user has clicked a comment line. If the user has clicked a host entry line, the Ping option appears in the pop-up menu. At B in Listing 2, the subroutine displays the pop-up menu, Menu_Popup.

If the user right-clicks a line past the end of the file, the error handler is invoked. The error handler transfers control to the end of the subroutine and bypasses the code that displays the pop-up menu.

The HOSTS File Edit utility handles each of the pop-up menu's eight options (Insert, Edit, Cut, Copy, Paste, Delete, Ping, and Cancel) using VB's standard Menu_Click subroutine. For instance, selecting the Insert option executes the Menu_Insert_Click subroutine, selecting the Edit option executes the Menu_Edit_Click subroutine, and so on. Listing 3 shows the Menu_Edit_Click subroutine.

At A in Listing 3, Menu_Edit_Click checks the first character of the line for a number. If the first character is a number, the user has clicked a host entry line; otherwise, the user has clicked a comment line. At D in Listing 3, page 208, you can see the code that executes if the selected line is a comment line: The subroutine moves the line into the Text_Comments text box on the Form_Comment form, and displays the form.

If the line is a host entry, the subroutine executes the code that starts at B in Listing 3. The subroutine extracts the IP address from the string that contains the selected list item text and moves the IP address into the sTemp string variable. Then the SelText method of the MaskEdBox_IPAddress masked edit text box loads the contents of sTemp into the masked edit text box on Form_Edit. This box contains the code for the Edit HOSTS File Entry dialog box in Screen 2. Form_Edit uses a masked edit text box to ensure that the TCP/IP address is in the correct format.

The code at C in Listing 3 checks whether a comment resides on the line with the host entry. (A comment must begin with the pound character, #.) If there is a comment, the subroutine moves it into the Text_Comment text box on Form_Edit.

Next, the subroutine moves the TCP/IP host name into the Text_HostName text box on Form_Edit. Finally, Menu_Edit_Click displays Form_Edit as the Edit HOSTS File Entry dialog box.

The HOSTS File Edit program uses the Edit HOSTS File Entry dialog box for making new entries in the HOSTS file as well as for modifying existing entries. Depending on whether the user selects the Insert option or the Edit option on the main editing screen, clicking OK in the Edit HOSTS File Entry dialog box either inserts a new entry or replaces an existing entry in the HOSTS file. In both cases, the HOSTS File Edit program concatenates the contents of the MaskEdBox_IPAddress, Text_HostName, and Text_Comment objects into a string and adds it to the list.

The Ping Option
The Edit HOSTS File Entry dialog box includes the Ping button that lets the user ping a remote host and verify that the host can be contacted. Clicking Ping displays Screen 3 and activates the Command_Ping list button, which initiates the Ping_List subroutine in Listing 4.

At A in Listing 4, Ping_List uses a For ... Next loop to ping the target system four times. Within the loop at B in Listing 4, you can see where the subroutine calls the ping function declared in ping32.dll to ping the remote system. The first parameter of the ping function, string variable sIPAddress, contains the IP address entered in the masked edit text box on the Edit HOSTS File Entry screen. The second parameter, string variable sIP, returns the IP address from the remote host. Before issuing the ping, the subroutine sizes sIP to 16, the maximum size of the returned IP address. The third parameter specifies the size of the data packet that will be pinged. In this example, 32-byte packets are sent back and forth between the local and remote TCP/IP systems. The fourth parameter, long variable lPingTime, returns the amount of time required to complete the ping function. The fifth parameter specifies the maximum timeout value in milliseconds. In this case, the ping times out after 2 seconds (2000 milliseconds). The last parameter of the ping function controls whether the function will be executed in verbose or silent mode. A 0 value specifies silent mode; a 1 specifies verbose mode, which is useful for debugging the execution of the ping function. After the ping function completes, subroutine Ping_List checks the return code for an error. If no error occurred, the subroutine adds an item to the List_PingStatus list showing the time required to complete the ping. If an error occurred, the subroutine adds a failure message and the ping return code to the List_PingStatus list.

At C in Listing 4, the subroutine posts the summary status of the ping results in the List_PingStatus list. If no errors occurred in any of the four ping attempts, Ping_List posts a success message. Similarly, if none of the ping attempts succeeded, Ping_List posts a failure message. Otherwise, some ping attempts succeeded and others failed. In this case, Ping_List posts the message "Host Verified with error" to the List_PingStatus list.

After completing all HOSTS file changes, the user can select the Save option from the File menu to write the changes to the HOSTS file. The utility does not save changes until the user selects the Save option. Clicking the Close button in the window's upper right corner or the program icon in the upper left corner closes the HOSTS File Edit program and discards changes. Listing 5 shows the Menu_Save_Click subroutine, which writes the file to the disk.

In the Menu_Save_Click subroutine, the Open function opens the HOSTS file for output. The sHostsFilePath string variable (set during the initial form load in Listing 1) contains the filename and directory path to the HOSTS file. After opening the HOSTS file, the subroutine employs a Do While loop to traverse the List_HOSTS list (which contains the updated contents of the HOSTS file) and to write each entry to the HOSTS file. After the Do While loop completes, the subroutine closes the file.

Easy HOSTS File Editing
The HOSTS File Edit utility provides a safe, easy-to-use mechanism for updating a local HOSTS file. Unlike a standard text editor, the HOSTS File Edit utility lets you verify the TCP/IP addresses written to the HOSTS file, as well as ensure that the data written to the HOSTS file is correctly formatted. Stay tuned to Windows NT Magazine for other VB utilities that help you solve common business problems.