-
Notifications
You must be signed in to change notification settings - Fork 12
/
local_listener.go
56 lines (48 loc) · 1.27 KB
/
local_listener.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
// Copyright 2020 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net
import (
"fmt"
"net"
"github.com/searKing/golang/go/errors"
)
var Ipv4LoopbackHosts = []string{"localhost", "127.0.0.1"}
var Ipv6LoopbackHosts = []string{"localhost", "[::1]", "::1"}
func IsLoopbackHost(host string) bool {
for _, v := range Ipv4LoopbackHosts {
if host == v {
return true
}
}
for _, v := range Ipv6LoopbackHosts {
if host == v {
return true
}
}
return false
}
// LoopbackListener returns a loopback listener on a first usable port in ports or 0 if ports is empty
func LoopbackListener(ports ...string) (net.Listener, error) {
var errs []error
if len(ports) == 0 {
ports = append(ports, "0")
}
for _, port := range ports {
for _, host := range Ipv4LoopbackHosts {
l, err := net.Listen("tcp", net.JoinHostPort(host, port))
if err == nil {
errs = append(errs, err)
return l, nil
}
}
for _, host := range Ipv6LoopbackHosts {
l, err := net.Listen("tcp6", net.JoinHostPort(host, port))
if err == nil {
errs = append(errs, err)
return l, nil
}
}
}
return nil, fmt.Errorf("net: failed to listen on ports: %v", errors.Multi(errs...))
}