mirror of
https://github.com/lingble/talos.git
synced 2025-11-30 04:43:39 +00:00
This removes the github.com/pkg/errors package in favor of the official error wrapping in go 1.13. Signed-off-by: Andrew Rynhard <andrew@andrewrynhard.com>
69 lines
1.4 KiB
Go
69 lines
1.4 KiB
Go
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
|
|
|
package net
|
|
|
|
import (
|
|
"errors"
|
|
"net"
|
|
)
|
|
|
|
// IPAddrs finds and returns a list of non-loopback IPv4 addresses of the
|
|
// current machine.
|
|
func IPAddrs() (ips []net.IP, err error) {
|
|
ips = []net.IP{}
|
|
|
|
addrs, err := net.InterfaceAddrs()
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
for _, a := range addrs {
|
|
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
|
if ipnet.IP.To4() != nil {
|
|
ips = append(ips, ipnet.IP)
|
|
}
|
|
}
|
|
}
|
|
|
|
return ips, nil
|
|
}
|
|
|
|
// FormatAddress checks that the address has a consistent format.
|
|
func FormatAddress(addr string) string {
|
|
if ip := net.ParseIP(addr); ip != nil {
|
|
// If this is an IPv6 address, encapsulate it in brackets
|
|
if ip.To4() == nil {
|
|
return "[" + ip.String() + "]"
|
|
}
|
|
|
|
return ip.String()
|
|
}
|
|
|
|
return addr
|
|
}
|
|
|
|
// NthIPInNetwork takes an IPNet and returns the nth IP in it.
|
|
func NthIPInNetwork(network *net.IPNet, n int) (net.IP, error) {
|
|
ip := network.IP
|
|
dst := make([]byte, len(ip))
|
|
copy(dst, ip)
|
|
|
|
for i := 0; i < n; i++ {
|
|
for j := len(dst) - 1; j >= 0; j-- {
|
|
dst[j]++
|
|
|
|
if dst[j] > 0 {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if network.Contains(dst) {
|
|
return dst, nil
|
|
}
|
|
|
|
return nil, errors.New("network does not contain enough IPs")
|
|
}
|