9

How would a program in C++/ C / C# program change the C:\Windows\System32\drivers\etc\hosts file content in windows? I know this sounds like phishing, honestly not.

Mubsher Mughal
  • 402
  • 6
  • 18
JRDH
  • 107
  • 1
  • 1
  • 2

6 Answers6

15

Hosts file has a very simple format where each line may contain "ip host" records

All you need is regular file appending :

using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
    w.WriteLine("123.123.123.123 FQDN");
}

Beware that by default you'll need elevated privileges to write to the hosts file...

In order to revert back, better take a backup of the file and restore it once you are done.

whihathac
  • 1,692
  • 1
  • 22
  • 37
Lotfi
  • 1,197
  • 6
  • 18
14

First, you should request for administrative permission from the user. You can do this through your Program class in your application. The below code will request the user for administrative access, the user then has the option to allow or deny it. If they deny it, this example does not run the application.

Once your application is run in administrative mode, its plain text with simple formatting. You do not even need all the Microsoft comments included in the file, and simple string parsing will do just fine. The comments by MSFT in the HOSTS file are all the documentation you really need as far as the HOSTS file itself goes.

namespace Setup {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using Setup.Forms;
    using System.Security.Principal;
    using System.Diagnostics;

    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!administrativeMode) {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.Verb = "runas";
                startInfo.FileName = Application.ExecutablePath;
                try {
                    Process.Start(startInfo);
                }
                catch {
                    return;
                }
                return;
            }

            Application.Run(new ShellForm());
        }
    }
}
David Anderson
  • 12,975
  • 5
  • 47
  • 72
  • 2
    Note that by copying your code here it's effectively released under CC-Wiki. The copyright block is ineffective. Not sure if you want to remove the copyright block or the whole answer.... – Billy ONeal Jun 29 '11 at 21:38
  • 1
    I own DCOM Productions and I just copied the entire contents of the file for a quick answer. Either way it doesn't matter, just using it to give him an approach to his question. If I didn't want him to use the code I wouldn't have posted at all. ;) – David Anderson Jun 29 '11 at 23:11
  • Okay. :) Just didn't want you to inadvertently release your IP under a less restrictive license than you intended. – Billy ONeal Jun 29 '11 at 23:15
  • Ah, no biggy. The project it came from is a framework I've been writing for a few years now and will probably go open source by the end of July – David Anderson Jun 29 '11 at 23:17
  • 1
    Can you [edit](http://stackoverflow.com/posts/6527486/edit) your answer to remove the notification? Its just drawing unnecessary attention (mod flags and [meta questions](http://meta.stackexchange.com/questions/96952/should-copyright-notices-and-licenses-in-code-be-removed)) –  Jun 30 '11 at 13:24
9

The file is usually located at C:\Windows\System32\drivers\etc\hosts. Rather than hard coding the C:\Windows part though, you should use Environment.GetEnvironmentVariable("SystemRoot") to safely determine the system root directory.

Otherwise you can write to it like any other file, assuming you have the proper permissions.

Eric Petroelje
  • 57,359
  • 8
  • 118
  • 174
4

The hosts file is just plain text. The format is each line contains the IP and the hostname that IP should resolve to, separated by whitespace. # denotes a comment.

Example:

# This is a comment-
127.0.0.1    mysuperhost.com

The file is located here: C:\Windows\system32\drivers\etc\hosts. You will (with good reason), need administrator privileges to write to it.

driis
  • 151,614
  • 43
  • 262
  • 332
3

The most accurate way of finding the HOSTS file location is to read the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath registry key, and appending hosts to the end.

This will always point to the correct location for the current machine configuration and works for all Windows NT based platforms since Windows NT 4.0.

Kristian Williams
  • 2,034
  • 20
  • 22
  • Unfortunately this does not seem to be the case with the more modern operating systems. Specifically on Windows 7, if you change the DataBasePath value, it will not use the new location. – pk. May 01 '14 at 19:30
  • 2
    Whether changing the value affects it (or if Microsoft even supports doing so) isn't an issue. The question was how to edit the current hosts file, I simply gave the most reliable way to find said file. (Assuming you've not been messing in the registry.) For the given purpose, this method is valid from Windows NT 4.0 up to and including Windows 8.1 Update 1 – Kristian Williams Jun 18 '14 at 12:32
2

As a guy who struggled with this problem, easy way out, copy the hosts file to temp folder, modify it and copy it back with overwrite. Running the application as admin, will be the best.

Jishnu U Nair
  • 492
  • 4
  • 11
  • 27
  • 1
    ... This answer is like going onto a car repair forum and telling the OP, "The easy way out is to start walking to your destinations instead of fixing your car." – Shadoninja Mar 29 '16 at 22:54