forked from iotexproject/go-p2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
44 lines (40 loc) · 919 Bytes
/
util.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
package p2p
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"net"
)
// EnsureIPv4 returns an IPv4 address regardless the input is a IPv4 address or host name. If the host name has multiple
// IPv4 address be associated, a random one will be returned.
func EnsureIPv4(ipOrHost string) (string, error) {
ip := net.ParseIP(ipOrHost)
if ip != nil {
if ip.To4() == nil {
return "", fmt.Errorf("%s is IPv6 address", ipOrHost)
}
return ipOrHost, nil
}
addrs, err := net.LookupHost(ipOrHost)
if err != nil {
return "", err
}
ips := make([]string, 0)
for _, addr := range addrs {
if ip := net.ParseIP(addr); ip != nil {
if ip.To4() == nil {
continue
}
ips = append(ips, addr)
}
}
if len(ips) == 0 {
return "", errors.New("no IPv4 address found")
}
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(ips))))
if err != nil {
return "", err
}
return ips[n.Int64()], nil
}