feat: 工具模块ping功能

This commit is contained in:
TsMask
2024-10-10 21:05:12 +08:00
parent 9127865b12
commit 7ba111a7e9
4 changed files with 500 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
package model
import (
"runtime"
"time"
probing "github.com/prometheus-community/pro-bing"
)
// Ping 探针发包参数
type Ping struct {
DesAddr string `json:"desAddr" binding:"required"` // 目的 IP 地址(字符串类型,必填)
SrcAddr string `json:"srcAddr"` // 源 IP 地址(字符串类型,可选)
Interval int `json:"interval"` // 发包间隔整数类型可选单位取值范围1-60默认值1
TTL int `json:"ttl"` // TTL整数类型可选取值范围1-255默认值255
Count int `json:"count"` // 发包数整数类型可选取值范围1-65535默认值5
Size int `json:"size"` // 报文大小整数类型可选取值范围36-8192默认值36
Timeout int `json:"timeout"` // 报文超时时间整数类型可选单位取值范围1-60默认值2
}
// setDefaultValue 设置默认值
func (p *Ping) setDefaultValue() {
if p.Interval < 1 || p.Interval > 10 {
p.Interval = 1
}
if p.TTL < 1 || p.TTL > 255 {
p.TTL = 255
}
if p.Count < 1 || p.Count > 65535 {
p.Count = 5
}
if p.Size < 36 || p.Size > 8192 {
p.Size = 36
}
if p.Timeout < 1 || p.Timeout > 60 {
p.Timeout = 2
}
}
// NewPinger ping对象
func (p *Ping) NewPinger() (*probing.Pinger, error) {
p.setDefaultValue()
pinger, err := probing.NewPinger(p.DesAddr)
if err != nil {
return nil, err
}
if p.SrcAddr != "" {
pinger.Source = p.SrcAddr
}
pinger.Interval = time.Duration(p.Interval) * time.Second
pinger.TTL = p.TTL
pinger.Count = p.Count
pinger.Size = p.Size
pinger.Timeout = time.Duration(p.Timeout) * time.Second
// 设置特权模式(需要管理员权限)
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
return pinger, nil
}