Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
JRDH Avatar asked Jun 29 '11 21:06

JRDH


2 Answers

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.

like image 52
Lotfi Avatar answered Oct 26 '22 03:10

Lotfi


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());
        }
    }
}
like image 38
David Anderson Avatar answered Oct 26 '22 04:10

David Anderson