github.com/Mrs4s/MiraiGo@v0.0.0-20240226124653-54bdd873e3fe/utils/tcping.go (about)

     1  package utils
     2  
     3  import (
     4  	"net"
     5  	"time"
     6  )
     7  
     8  type ICMPPingResult struct {
     9  	PacketsSent int
    10  	PacketsLoss int
    11  	AvgTimeMill int64
    12  }
    13  
    14  // RunTCPPingLoop 使用 tcp 进行 ping
    15  func RunTCPPingLoop(ipport string, count int) (r ICMPPingResult) {
    16  	r = ICMPPingResult{
    17  		PacketsSent: count,
    18  		PacketsLoss: count,
    19  		AvgTimeMill: 9999,
    20  	}
    21  	if count <= 0 {
    22  		return
    23  	}
    24  	durs := make([]int64, 0, count)
    25  	for i := 0; i < count; i++ {
    26  		d, err := tcping(ipport)
    27  		if err == nil {
    28  			r.PacketsLoss--
    29  			durs = append(durs, d)
    30  		}
    31  		time.Sleep(time.Millisecond * 100)
    32  	}
    33  
    34  	if len(durs) > 0 {
    35  		r.AvgTimeMill = 0
    36  		for _, d := range durs {
    37  			r.AvgTimeMill += d
    38  		}
    39  		if len(durs) > 1 {
    40  			r.AvgTimeMill /= int64(len(durs))
    41  		}
    42  	}
    43  
    44  	return
    45  }
    46  
    47  func tcping(ipport string) (int64, error) {
    48  	t := time.Now().UnixMilli()
    49  	conn, err := net.DialTimeout("tcp", ipport, time.Second*10)
    50  	if err != nil {
    51  		return 9999, err
    52  	}
    53  	_ = conn.Close()
    54  	return time.Now().UnixMilli() - t, nil
    55  }