Building a Graphical HOSTS File Edit Utility

Here's a simple HOSTS file editing utility that you can build with VB to correctly format HOSTS file entries and verify host names and IP addresses.

Michael Otey

November 30, 1997

11 Min Read
ITPro Today logo


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 tolet TCP/IP applications reference other systems in your network via meaningfulnames, instead of hard-to-remember numeric IP addresses. If a network has a DNSserver, 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 theHOSTS 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 texteditor such as Notepad. Although this method works, editing the HOSTS file witha text editor has some serious limitations. First, the HOSTS file has somesubtle 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 filemust be correct; a standard text editor has no mechanism to ensure that youenter valid values. This month's VB Solutions utility, HOSTS File Edit, makesediting the HOSTS file a less error-prone process because it correctly formatsthe 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 contentsof the HOSTS file in this window. Unlike a standard ASCII text editor, HOSTSFile Edit doesn't let you directly type over the HOSTS file lines. Instead, youright-click the line you want to modify, and the program displays the pop-upmenu you see in Screen 1. The menu options let you insert a new line; edit anexisting line; or cut, copy, paste, or delete a line. If you right-click a linewith an active IP address and host name, you also get the option to ping theremote host.

To add a new entry to the HOSTS file, you right-click the place where youwant to insert the line and then select the menu's Insert option to display theEdit HOSTS File Entry dialog box shown in Screen 2, page 206. The utilityformats the IP address, host name, and optional comment that you enter in thisdialog box. (You must enter the IP address in the standard xxx.xxx.xxx.xxxformat.) Clicking OK inserts the new entry in the HOSTS file and closes thedialog 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 placesthe entry in the first position, which most TCP/IP applications that use theHOSTS file require. If you click Ping, the utility pings the remote host nameyou entered and verifies that the IP address is correct. (Clicking Ping isoptional; thus, you can enter systems into the HOSTS file regardless of whetheryou are connected to them.) Screen 3, page 206, shows the Ping Host verificationscreen that displays when you click Ping. If the ping is not successful, theutility 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 waysin which the utility differs from a standard text editor is that the utilitylets you ping remote hosts and verify the host name and IP address. HOSTS FileEdit implements this ping capability using ping32.dll, a DLL based on the ping.csample that Microsoft distributes in its Winsock development sample. (Fordetails about ping32.dll, see VB Solutions: "Building an Automated MassPing 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 thename or the IP address of the system to be pinged. The second parameter is astring that the ping function returns. This string contains the IP address ofthe pinged system. This parameter lets the calling program retrieve the IPaddress for a given TCP/IP host name. The third parameter specifies the size ofthe data packet sent with the ping. The maximum data length that ping32.dllallows is 1024 bytes. The fourth parameter, a long variable, returns the elapsedmilliseconds the ping function required to execute. The fifth parameter containsthe maximum time in milliseconds that the ping function waits for a response forsent or received packets. The sixth parameter specifies the mode of operationfor the ping function. If you set this parameter to True, ping32.dll runs inverbose mode, the mode that displays all ping results and errors in a messagebox. Setting the sixth parameter to False runs ping32.dll in silent mode, themode that reports any ping results and errors in the ping function's return codeand output parameters. (You can download ping32.dll, its source code, and thecode for the HOSTS File Edit utility from the Windows NT Magazine Website at http://www.winntmag.com.)

When HOSTS File Edit starts, it executes the Form_Load subroutine inListing 1. At callout A in Listing 1, you can see where the GetSystem32Dirfunction returns a string containing the path of the NT system directory,winntsystem32. The GetSystem32Dir function uses the Win32 GetSystemDirectoryAAPI to dynamically retrieve the directory's path. The code at A appends theHOSTS file path to the system directory path and assigns this result to thesHostsFilePath 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 movethe contents into the sTextLine variable. The AddItem method adds each line tothe 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'smain window (Screen 1).

As I mentioned previously, to edit the HOSTS file, you right-click in theHOSTS 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 handlingleft-clicks. To display the pop-up menu after the right-click, I use theMouseDown function of the List_HOSTS list box control. Listing 2 shows theList_HOSTS_MouseDown subroutine.

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

At A in Listing 2, the subroutine checks the first character of the line todetermine whether it's a numeric value. If the first character is numeric, theuser has clicked a line that contains a host entry (a host entry must alwaysbegin in the first position of the HOSTS file). Otherwise, the user has clickeda comment line. If the user has clicked a host entry line, the Ping optionappears in the pop-up menu. At B in Listing 2, the subroutine displays thepop-up menu, Menu_Popup.

If the user right-clicks a line past the end of the file, the error handleris invoked. The error handler transfers control to the end of the subroutine andbypasses 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 standardMenu_Click subroutine. For instance, selecting the Insert option executes theMenu_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 linefor a number. If the first character is a number, the user has clicked a hostentry 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 commentline: The subroutine moves the line into the Text_Comments text box on theForm_Comment form, and displays the form.

If the line is a host entry, the subroutine executes the code that startsat B in Listing 3. The subroutine extracts the IP address from the string thatcontains the selected list item text and moves the IP address into the sTempstring variable. Then the SelText method of the MaskEdBox_IPAddress masked edittext 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 inthe correct xxx.xxx.xxx.xxx format.

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

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

The HOSTS File Edit program uses the Edit HOSTS File Entry dialog box formaking 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 onthe main editing screen, clicking OK in the Edit HOSTS File Entry dialog boxeither inserts a new entry or replaces an existing entry in the HOSTS file. Inboth cases, the HOSTS File Edit program concatenates the contents of theMaskEdBox_IPAddress, Text_HostName, and Text_Comment objects into astring and adds it to the list.

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

At A in Listing 4, Ping_List uses a For ... Next loop to ping the targetsystem four times. Within the loop at B in Listing 4, you can see where thesubroutine calls the ping function declared in ping32.dll to ping the remotesystem. The first parameter of the ping function, string variable sIPAddress,contains the IP address entered in the masked edit text box on the Edit HOSTSFile Entry screen. The second parameter, string variable sIP, returns the IPaddress from the remote host. Before issuing the ping, the subroutine sizes sIPto 16, the maximum size of the returned IP address. The third parameterspecifies 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/IPsystems. The fourth parameter, long variable lPingTime, returns the amount oftime required to complete the ping function. The fifth parameter specifies themaximum timeout value in milliseconds. In this case, the ping times out after 2seconds (2000 milliseconds). The last parameter of the ping function controlswhether the function will be executed in verbose or silent mode. A 0 valuespecifies silent mode; a 1 specifies verbose mode, which is useful for debuggingthe 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 timerequired to complete the ping. If an error occurred, the subroutine adds afailure message and the ping return code to the List_PingStatus list.

At C in Listing 4, the subroutine posts the summary status of the pingresults in the List_PingStatus list. If no errors occurred in any of the fourping attempts, Ping_List posts a success message. Similarly, if none of the pingattempts succeeded, Ping_List posts a failure message. Otherwise, some pingattempts 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 Saveoption from the File menu to write the changes to the HOSTS file. The utilitydoes not save changes until the user selects the Save option. Clicking the Closebutton in the window's upper right corner or the program icon in the upper leftcorner closes the HOSTS File Edit program and discards changes. Listing 5 showsthe Menu_Save_Click subroutine, which writes the file to the disk.

In the Menu_Save_Click subroutine, the Open function opens the HOSTS filefor output. The sHostsFilePath string variable (set during the initial form loadin Listing 1) contains the filename and directory path to the HOSTS file. Afteropening the HOSTS file, the subroutine employs a Do While loop to traverse theList_HOSTS list (which contains the updated contents of the HOSTS file) and towrite each entry to the HOSTS file. After the Do While loop completes, thesubroutine closes the file.

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

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like