Add Windows support

This commit is contained in:
maride 2025-12-19 16:54:22 +01:00
parent b888054b05
commit 3fbf6b1474
2 changed files with 22 additions and 8 deletions

View File

@ -8,6 +8,7 @@
- Deduplication
- Format check
- `SUID` safe!
- Supports *NIX (Linux & macOS) and Windows
## Usage

29
main.go
View File

@ -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("+-------------------------+")
}