Search for entry in Hosts file
Keywords: Search for entry in Hosts file
Question:
Need to remove an entry in the hosts file on workstations. e.g. "127.0.0.1 localhost" How to search for the above entry in the hosts file and if it present, remove it.Answer:
NB: You generally need admin access to update the hosts file (on NT/2000/XP).;autoupdate hosts file. ;Removehost udf that does the hard work #DefineFunction RemoveHost(bb,hostname) ptr=BinaryIndexEx(bb,0,hostname,@FWDSCAN,@FALSE) If ptr==-1 Then Return(0) ;found one. find beginning of line ptra=BinaryIndexEx(bb,ptr,@LF,@BACKSCAN,@TRUE) If ptra == -1 Then ptra=0 Else ptra=ptra+1 ;find end of line ptrb=BinaryIndexEx(bb,ptr,@LF,@FWDSCAN,@TRUE) If ptrb==-1 Then ptrb=BinaryEodGet(bb)-1 Else ptrb=ptrb+1 ;Move data BinaryCopy(bb,ptra,bb,ptrb,BinaryEodGet(bb)-ptrb) ;Set new EOD BinaryEodSet(bb,BinaryEodGet(bb)-(ptrb-ptra)) Return (1) #EndFunction ;Determine HOSTS file location ;Windows 95/98/Me c:\windows\hosts ;Windows NT/2000/XP Pro c:\winnt\system32\drivers\etc\hosts ;Windows XP Home c:\windows\system32\drivers\etc\hosts If WinVersion(4)==4 ; NT family HOSTS=StrCat(DirWindows(1),"drivers\etc\hosts") Else HOSTS=StrCat(DirWindows(0),"hosts") EndIf ;Message("Debug - hosts file name",hosts) fs=FileSize(hosts) bb=BinaryAlloc(fs) BinaryRead(bb,hosts) ;locate removeme RemoveHost(bb,"hjem.get2net.dk") RemoveHost(bb,"hjeq.get2net.dk") RemoveHost(bb,"www.abc.com") RemoveHost(bb,"www.def.net") ErrorMode(@OFF) byteswritten=BinaryWrite(bb,hosts) ErrorMode(@CANCEL) BinaryFree(bb) If byteswritten==0 Message("Error","Could not write to hosts file") Else Message("Hosts file update","Complete") EndIf