简体   繁体   中英

How do i change the hosts file in a windows program?

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.

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.

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());
        }
    }
}

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM