github.com/GuanceCloud/cliutils@v1.1.21/network/port.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  // Package network wraps basic network related implements.
     7  package network
     8  
     9  import (
    10  	"fmt"
    11  	"log"
    12  	"net"
    13  	"strconv"
    14  	"strings"
    15  	"time"
    16  )
    17  
    18  func PortInUse(ipport string, timeout time.Duration) bool {
    19  	c, err := net.DialTimeout(`tcp`, ipport, timeout)
    20  	if err != nil {
    21  		log.Printf("[error] %s", err.Error())
    22  		return false
    23  	}
    24  
    25  	log.Printf("[debug] port %s used under TCP", ipport)
    26  
    27  	defer func() {
    28  		if err := c.Close(); err != nil {
    29  			_ = err // pass
    30  		}
    31  	}()
    32  	return true
    33  }
    34  
    35  func ParseListen(listen string) (ip string, port int64, err error) {
    36  	parts := strings.Split(listen, `:`)
    37  
    38  	if len(parts) == 1 { //nolint:gomnd // 只有 port 部分
    39  		port, err = strconv.ParseInt(parts[0], 10, 16)
    40  		if err != nil {
    41  			err = fmt.Errorf("invalid listen addr: %s", listen)
    42  		}
    43  
    44  		return
    45  	}
    46  
    47  	if len(parts) != 2 { //nolint:gomnd
    48  		err = fmt.Errorf("invalid listen addr: %s", listen)
    49  		return
    50  	}
    51  
    52  	port, err = strconv.ParseInt(parts[1], 10, 16)
    53  	if err != nil {
    54  		err = fmt.Errorf("invalid listen addr: %s", listen)
    55  		return
    56  	}
    57  
    58  	ip = parts[0]
    59  
    60  	return
    61  }