-
Notifications
You must be signed in to change notification settings - Fork 6
/
ip_address.go
49 lines (42 loc) · 1.21 KB
/
ip_address.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ipaddress
import (
"fmt"
"net"
"github.com/UpCloudLtd/upcloud-cli/v3/internal/commands"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud"
)
const maxIPAddressActions = 10
// BaseIPAddressCommand creates the base 'ip-address' command
func BaseIPAddressCommand() commands.Command {
return &ipAddressCommand{
commands.New("ip-address", "Manage IP addresses"),
}
}
type ipAddressCommand struct {
*commands.BaseCommand
}
// InitCommand implements Command.InitCommand
func (i *ipAddressCommand) InitCommand() {
i.Cobra().Aliases = []string{"ip"}
}
// GetFamily returns a human-readable string (`"IPv4"` or `"IPv6"`) of the address family of the ip parsed from the string
func GetFamily(address string) (string, error) {
parsed := net.ParseIP(address)
if parsed.To4() != nil {
return upcloud.IPAddressFamilyIPv4, nil
}
if parsed.To16() != nil {
return upcloud.IPAddressFamilyIPv6, nil
}
ip, _, err := net.ParseCIDR(address)
if err != nil {
return "", fmt.Errorf("%s is an invalid ip address", address)
}
if ip.To4() != nil {
return upcloud.IPAddressFamilyIPv4, nil
}
if ip.To16() != nil {
return upcloud.IPAddressFamilyIPv6, nil
}
return "", fmt.Errorf("%s is an invalid ip address", address)
}