Root

github.com/txn2/txeh

Package txeh provides /etc/hosts file management capabilities.

import "github.com/txn2/txeh"

Package txeh provides /etc/hosts file management capabilities. It offers a simple interface for adding, removing, and querying hostname-to-IP mappings with thread-safe operations and cross-platform support (Linux, macOS, Windows).

Constants

Line type constants for HostFileLine.

Source: txeh.go:20

const (
	UNKNOWN = 0  // Unknown line type.
	EMPTY   = 10 // Empty line.
	COMMENT = 20 // Comment line starting with #.
	ADDRESS = 30 // Address line with IP and hostnames.
)

DefaultMaxHostsPerLineWindows is the default maximum number of hostnames per line on Windows. Windows has a limitation where lines with more than ~9 hostnames may not resolve correctly.

Source: txeh.go:28

const DefaultMaxHostsPerLineWindows = 9

IP address family constants.

Source: txeh.go:38

const (
	IPFamilyV4 IPFamily = iota // IPv4 address family.
	IPFamilyV6                 // IPv6 address family.
)

Functions

func ExecCommandFunc() func(string, ...string) *exec.Cmd

Source: flush.go:14

ExecCommandFunc returns the current exec command function. This is intended for test code that needs to save and restore the original.

func FlushDNSCache() error

Source: flush.go:52

FlushDNSCache flushes the operating system's DNS cache.

Platform commands (all are OS-provided utilities, not installable dependencies):

  • macOS: dscacheutil -flushcache + killall -HUP mDNSResponder (ships with macOS)
  • Linux: resolvectl flush-caches (systemd 239+) or systemd-resolve --flush-caches (older systemd). Returns ErrNoResolver if neither binary is found, which typically means the system does not cache DNS locally and hosts file changes take effect immediately.
  • Windows: ipconfig /flushdns (ships with Windows)

Returns a *FlushError on failure, or nil on unsupported platforms where no resolver is detected.

func NewHosts(hc *HostsConfig) (*Hosts, error)

Source: txeh.go:95

NewHosts returns a new hosts object.

func NewHostsDefault() (*Hosts, error)

Source: txeh.go:90

NewHostsDefault returns a hosts object with default configuration.

func ParseHosts(path string) ([]HostFileLine, error)

Source: txeh.go:566

ParseHosts reads and parses a hosts file from the given path.

func ParseHostsFromString(input string) ([]HostFileLine, error)

Source: txeh.go:575

ParseHostsFromString parses hosts file content from a string.

func SetExecCommandFunc(fn func(string, ...string) *exec.Cmd)

Source: flush.go:20

SetExecCommandFunc replaces the exec command function. This is intended for test code that needs to mock command execution.

Types

type AddressLocations

Source: txeh.go:69

AddressLocations maps an address to its location in the HFL.

type AddressLocations map[string]int

type FlushError

Source: flush.go:25

FlushError represents a DNS cache flush failure with platform context.

type FlushError struct {
	Platform string
	Command  string
	Err      error
}
Fields
  • Platform string
  • Command string
  • Err error

func Error) Error() string

Source: flush.go:32

Error returns a human-readable error message.

func Unwrap() error

Source: flush.go:37

Unwrap returns the underlying error.

type HostFileLine

Source: txeh.go:78

HostFileLine represents a single line in a hosts file.

type HostFileLine struct {
	OriginalLineNum int
	LineType        int
	Address         string
	Parts           []string
	Hostnames       []string
	Raw             string
	Trimmed         string
	Comment         string
}
Fields
  • OriginalLineNum int
  • LineType int
  • Address string
  • Parts []string
  • Hostnames []string
  • Raw string
  • Trimmed string
  • Comment string

type HostFileLines

Source: txeh.go:75

HostFileLines is a slice of HostFileLine entries.

type HostFileLines []HostFileLine

type HostLocations

Source: txeh.go:72

HostLocations maps a hostname to an original line number.

type HostLocations map[string]int

type Hosts

Source: txeh.go:62

Hosts represents a parsed hosts file with thread-safe operations.

type Hosts struct {
	*HostsConfig
	// contains filtered or unexported fields
}
Fields
  • *HostsConfig

func AddHost(addressRaw, hostRaw string)

Source: txeh.go:331

AddHost adds a host to an address and removes the host from any existing address it may be associated with.

func AddHostWithComment(addressRaw, hostRaw, comment string)

Source: txeh.go:340

AddHostWithComment adds a host to an address with an inline comment. The comment will appear after the hostnames on the line (e.g., "127.0.0.1 host # comment"). If the address already exists with the same comment, the host is appended to that line (respecting MaxHostsPerLine). If the address exists with a different comment, a new line is created with the specified comment.

func AddHosts(address string, hosts []string)

Source: txeh.go:313

AddHosts adds an array of hosts to the first matching address it finds or creates the address and adds the hosts.

func AddHostsWithComment(address string, hosts []string, comment string)

Source: txeh.go:323

AddHostsWithComment adds an array of hosts to an address with a comment. All hosts will share the same comment. If the address already exists with the same comment, hosts are appended to that line (respecting MaxHostsPerLine). If the address exists with a different comment, a new line is created.

func GetHostFileLines() HostFileLines

Source: txeh.go:527

GetHostFileLines returns a copy of all parsed host file lines.

func HostAddressLookup(host string, ipFamily IPFamily) (found bool, address string, idx int)

Source: txeh.go:483

HostAddressLookup returns true if the host is found, the address string, and the index of the host file line. This is part of the public API for consumers that need direct address lookups by IP family.

func ListAddressesByHost(hostname string, exact bool) [][]string

Source: txeh.go:420

ListAddressesByHost returns a list of IPs associated with a given hostname.

func ListHostsByCIDR(cidr string) [][]string

Source: txeh.go:441

ListHostsByCIDR returns a list of IPs and hostnames associated with a given CIDR.

func ListHostsByComment(comment string) []string

Source: txeh.go:464

ListHostsByComment returns all hostnames on lines with the given comment.

func ListHostsByIP(address string) []string

Source: txeh.go:404

ListHostsByIP returns a list of hostnames associated with a given IP address.

func Reload() error

Source: txeh.go:165

Reload re-reads the hosts file from disk and replaces the in-memory state. This is part of the public API for consumers who manage long-lived Hosts instances.

func RemoveAddress(address string)

Source: txeh.go:192

RemoveAddress removes all entries (lines) with the provided address.

func RemoveAddresses(addresses []string)

Source: txeh.go:183

RemoveAddresses removes all entries (lines) with the provided address.

func RemoveByComment(comment string)

Source: txeh.go:295

RemoveByComment removes all host entries that have the specified comment. This removes entire lines where the comment matches.

func RemoveByComments(comments []string)

Source: txeh.go:287

RemoveByComments removes all host entries that have any of the specified comments. This removes entire lines where the comment matches. This is part of the public API for bulk comment-based cleanup (e.g., kubefwd teardown).

func RemoveCIDRs(cidrs []string) error

Source: txeh.go:218

RemoveCIDRs Remove CIDR Range (Classless inter-domain routing) examples:

127.1.0.0/16  = 127.1.0.0  -> 127.1.255.255
127.1.27.0/24 = 127.1.27.0 -> 127.1.27.255

func RemoveFirstAddress(address string) bool

Source: txeh.go:199

RemoveFirstAddress removes the first entry (line) found with the provided address.

func RemoveFirstHost(host string) bool

Source: txeh.go:262

RemoveFirstHost removes the first hostname entry found and returns true if successful.

func RemoveHost(host string)

Source: txeh.go:255

RemoveHost removes all hostname entries of provided host.

func RemoveHosts(hosts []string)

Source: txeh.go:246

RemoveHosts removes all hostname entries of the provided host slice.

func RenderHostsFile() string

Source: txeh.go:513

RenderHostsFile returns the hosts file content as a formatted string.

func Save() error

Source: txeh.go:135

Save renders and writes the hosts file to the configured write path.

func SaveAs(fileName string) error

Source: txeh.go:140

SaveAs saves rendered hosts file to the filename specified.

type HostsConfig

Source: txeh.go:43

HostsConfig contains configuration for reading and writing hosts files.

type HostsConfig struct {
	ReadFilePath  string
	WriteFilePath string
	// RawText for input. If RawText is set ReadFilePath, WriteFilePath are ignored. Use RenderHostsFile rather
	// than save to get the results.
	RawText *string
	// MaxHostsPerLine limits the number of hostnames per line when adding hosts.
	// This is useful for Windows which has a limitation of ~9 hostnames per line.
	// Values:
	//   0  = auto-detect (Windows: 9, others: unlimited)
	//  -1  = force unlimited (no limit)
	//  >0  = explicit limit
	MaxHostsPerLine int
	// AutoFlush triggers a DNS cache flush after every successful Save/SaveAs.
	// Flush failures are returned as *FlushError, distinguishable via errors.As.
	AutoFlush bool
}
Fields
  • ReadFilePath string
  • WriteFilePath string
  • RawText *string

    RawText for input. If RawText is set ReadFilePath, WriteFilePath are ignored. Use RenderHostsFile rather than save to get the results.

  • MaxHostsPerLine int

    MaxHostsPerLine limits the number of hostnames per line when adding hosts. This is useful for Windows which has a limitation of ~9 hostnames per line. Values: 0 = auto-detect (Windows: 9, others: unlimited) -1 = force unlimited (no limit)

    0 = explicit limit

  • AutoFlush bool

    AutoFlush triggers a DNS cache flush after every successful Save/SaveAs. Flush failures are returned as *FlushError, distinguishable via errors.As.

type IPFamily

Source: txeh.go:34

IPFamily represents the IP address family (IPv4 or IPv6).

type IPFamily int64