-
Notifications
You must be signed in to change notification settings - Fork 49
/
helper.go
71 lines (58 loc) · 1.73 KB
/
helper.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2022 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/superproj/onex.
//
package options
import (
"fmt"
"net"
"strings"
netutils "k8s.io/utils/net"
)
// Define unit constant.
const (
_ = iota // ignore onex.iota
KiB = 1 << (10 * iota)
MiB
GiB
TiB
)
func join(prefixes ...string) string {
joined := strings.Join(prefixes, ".")
if joined != "" {
joined += "."
}
return joined
}
// ValidateAddress takes an address as a string and validates it.
// If the input address is not in a valid :port or IP:port format, it returns an error.
// It also checks if the host part of the address is a valid IP address and if the port number is valid.
func ValidateAddress(addr string) error {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("%q is not in a valid format (:port or ip:port): %w", addr, err)
}
if host != "" && netutils.ParseIPSloppy(host) == nil {
return fmt.Errorf("%q is not a valid IP address", host)
}
if _, err := netutils.ParsePort(port, true); err != nil {
return fmt.Errorf("%q is not a valid number", port)
}
return nil
}
// CreateListener create net listener by given address and returns it and port.
func CreateListener(addr string) (net.Listener, int, error) {
network := "tcp"
ln, err := net.Listen(network, addr)
if err != nil {
return nil, 0, fmt.Errorf("failed to listen on %v: %w", addr, err)
}
// get port
tcpAddr, ok := ln.Addr().(*net.TCPAddr)
if !ok {
_ = ln.Close()
return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
}
return ln, tcpAddr.Port, nil
}