Files
talos/pkg/net/net.go
Andrew Rynhard d430a37e46 refactor: use go 1.13 error wrapping
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>
2019-10-15 22:20:50 -07:00

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")
}