From 3fbf6b1474b480476868fc919e0c6c892f6f3277 Mon Sep 17 00:00:00 2001 From: maride Date: Fri, 19 Dec 2025 16:54:22 +0100 Subject: [PATCH] Add Windows support --- README.md | 1 + main.go | 29 +++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fd3fa88..8a2f912 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ - Deduplication - Format check - `SUID` safe! +- Supports *NIX (Linux & macOS) and Windows ## Usage diff --git a/main.go b/main.go index e792b88..d1cae80 100644 --- a/main.go +++ b/main.go @@ -5,14 +5,16 @@ import ( "net" "os" "regexp" + "runtime" "strings" "time" ) func main() { targetIP, domains := parseArgs() + targetFile := getHostsPath() motd() - process(targetIP, domains) + process(targetFile, targetIP, domains) } func parseArgs() (net.IP, []string) { @@ -45,12 +47,23 @@ func parseArgs() (net.IP, []string) { return ip, os.Args[2:] } -// process goes over the /etc/hosts and tries to best-fit the domain names for the IP -func process(ip net.IP, domains []string) { +// getHostsPath returns the path to the hosts file depending on the current operating system: +// /etc/hosts on *NIX, +// C:\Windows\system32\drivers\etc\hosts on WIN*. +func getHostsPath() (string) { + if runtime.GOOS == "windows" { + return "C:\\Windows\\system32\\drivers\\etc\\hosts" + } else { + return "/etc/hosts" + } +} + +// process goes over the targetFile and tries to best-fit the domain names for the IP +func process(targetFile string, ip net.IP, domains []string) { // Read file - bytesEtcHosts, readErr := os.ReadFile("/etc/hosts") + bytesEtcHosts, readErr := os.ReadFile(targetFile) if readErr != nil { - fmt.Fprintf(os.Stderr, "Failed to read /etc/hosts: %s\n", readErr.Error()) + fmt.Fprintf(os.Stderr, "Failed to read %s: %s\n", targetFile, readErr.Error()) os.Exit(1) } etcHosts := string(bytesEtcHosts) @@ -108,9 +121,9 @@ func process(ip net.IP, domains []string) { // Write out again newHosts := strings.Join(lines, "\n") - writeErr := os.WriteFile("/etc/hosts", []byte(newHosts), 0o644) + writeErr := os.WriteFile(targetFile, []byte(newHosts), 0o644) if writeErr != nil { - fmt.Fprintf(os.Stderr, "Failed to write /etc/hosts: %s\n", writeErr.Error()) + fmt.Fprintf(os.Stderr, "Failed to write %s: %s\n", targetFile, writeErr.Error()) os.Exit(1) } } @@ -131,6 +144,6 @@ func motd() { fmt.Println(" G H O S T ") fmt.Println(" your friendly helper with ") } - fmt.Println(" /etc/hosts, written in Go!") + fmt.Printf(" %cetc%chosts, written in Go!\n", os.PathSeparator, os.PathSeparator) // technically not fully correct, but the MOTD can only be *that* wide, right? fmt.Println("+-------------------------+") }