github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/net_utils.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package utils
     4  
     5  import (
     6  	"net"
     7  	"sort"
     8  )
     9  
    10  // ParseAddrHost 分析地址中的主机名部分
    11  func ParseAddrHost(addr string) string {
    12  	if len(addr) == 0 {
    13  		return addr
    14  	}
    15  
    16  	host, _, err := net.SplitHostPort(addr)
    17  	if err != nil {
    18  		return addr
    19  	}
    20  	return host
    21  }
    22  
    23  // MergePorts 聚合端口
    24  // 返回 [ [fromPort, toPort], ... ]
    25  func MergePorts(ports []int) [][2]int {
    26  	if len(ports) == 0 {
    27  		return nil
    28  	}
    29  
    30  	sort.Ints(ports)
    31  
    32  	var result = [][2]int{}
    33  	var lastRange = [2]int{0, 0}
    34  	var lastPort = -1
    35  	for _, port := range ports {
    36  		if port <= 0 /** 只处理有效的端口 **/ || port == lastPort /** 去重 **/ {
    37  			continue
    38  		}
    39  
    40  		if lastPort < 0 || port != lastPort+1 {
    41  			lastRange = [2]int{port, port}
    42  			result = append(result, lastRange)
    43  		} else { // 如果是连续的
    44  			lastRange[1] = port
    45  			result[len(result)-1] = lastRange
    46  		}
    47  
    48  		lastPort = port
    49  	}
    50  
    51  	return result
    52  }