github.com/searKing/golang/go@v1.2.117/net/local_listener.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package net 6 7 import ( 8 "fmt" 9 "net" 10 11 "github.com/searKing/golang/go/errors" 12 ) 13 14 var Ipv4LoopbackHosts = []string{"localhost", "127.0.0.1"} 15 var Ipv6LoopbackHosts = []string{"localhost", "[::1]", "::1"} 16 17 func IsLoopbackHost(host string) bool { 18 for _, v := range Ipv4LoopbackHosts { 19 if host == v { 20 return true 21 } 22 } 23 for _, v := range Ipv6LoopbackHosts { 24 if host == v { 25 return true 26 } 27 } 28 return false 29 } 30 31 // LoopbackListener returns a loopback listener on a first usable port in ports or 0 if ports is empty 32 func LoopbackListener(ports ...string) (net.Listener, error) { 33 var errs []error 34 if len(ports) == 0 { 35 ports = append(ports, "0") 36 } 37 38 for _, port := range ports { 39 for _, host := range Ipv4LoopbackHosts { 40 l, err := net.Listen("tcp", net.JoinHostPort(host, port)) 41 if err == nil { 42 errs = append(errs, err) 43 return l, nil 44 } 45 } 46 for _, host := range Ipv6LoopbackHosts { 47 l, err := net.Listen("tcp6", net.JoinHostPort(host, port)) 48 if err == nil { 49 errs = append(errs, err) 50 return l, nil 51 } 52 } 53 } 54 55 return nil, fmt.Errorf("net: failed to listen on ports: %v", errors.Multi(errs...)) 56 }