diff --git a/.golangci.yml b/.golangci.yml index c6c08ab9..10a1a810 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -91,12 +91,6 @@ linters-settings: - name: unconditional-recursion - name: waitgroup-by-value - staticcheck: - go: "1.20" - - unused: - go: "1.20" - output: sort-results: true @@ -113,7 +107,7 @@ linters: - errname - errorlint - exhaustive - - exportloopref + - copyloopvar - forcetypeassert - gocognit - goconst diff --git a/README.md b/README.md index 79a3d94b..ae610801 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,16 @@ It is not recommended, but it is possible for Smee to be run in `reservation` mo 1. All DHCP servers are configured to serve the same IP address and network boot details as Smee. In this scenario the DHCP functionality of Smee is redundant. It would be recommended to run Smee with the DHCP server functionality disabled (`-dhcp=false`). See the [doc](./docs/DHCP.md) on using your existing DHCP service for more details. +### Environment Variables and CLI Flags + +It's important to note that CLI flags take precedence over environment variables. All CLI flags can be set as environment variables. Environment variable names are the same as the flag names with some modifications. For example, the flag `-dhcp-addr` has the environment variable of `SMEE_DHCP_ADDR`. The modifications of CLI flags to environment variables are as follows: + +- prefixed with `SMEE_` +- all uppercase +- hyphens (`-`) are replaced with underscores (`_`) + +There is one environment variable that does not have a corresponding CLI flag. The environment variable is `SMEE_PUBLIC_IP_INTERFACE`. This environment variable takes a local network interface name and uses it to auto detect the IP address to use as the default in all other CLI flags that require an IP address. This is useful when the machine running Smee has multiple network interfaces and you want the default detected IP to be from this specified interface. + ### Local Setup Running the Tests diff --git a/cmd/smee/flag.go b/cmd/smee/flag.go index 2167b5e6..b723d893 100644 --- a/cmd/smee/flag.go +++ b/cmd/smee/flag.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "net" + "os" "regexp" "sort" "strings" @@ -175,7 +176,38 @@ func newCLI(cfg *config, fs *flag.FlagSet) *ffcli.Command { } } +// ipByInterface returns the first IPv4 address on the named network interface. +func ipByInterface(name string) string { + iface, err := net.InterfaceByName(name) + if err != nil { + return "" + } + + addrs, err := iface.Addrs() + if err != nil { + return "" + } + + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if !ok { + continue + } + + if ipNet.IP.To4() != nil { + return ipNet.IP.String() + } + } + + return "" +} + func detectPublicIPv4() string { + if netint := os.Getenv("SMEE_PUBLIC_IP_INTERFACE"); netint != "" { + if ip := ipByInterface(netint); ip != "" { + return ip + } + } ipDgw, err := autoDetectPublicIpv4WithDefaultGateway() if err == nil { return ipDgw.String()