在项目中,我们需要知道哪些IP是可用IP,这时候想到了用ICMP(Internet控制报文协议)。可以使用开源库–github.com/sparrc/go-ping来判断是否能ping通。

使用–github.com/sparrc/go-ping开源库判断是否能ping通的代码:

func ServerPing(target string) bool  {pinger, err := ping.NewPinger(target)if err != nil {panic(err)}pinger.Count = ICMPCOUNTpinger.Timeout = time.Duration(PINGTIME*time.Millisecond)pinger.SetPrivileged(true)pinger.Run()// blocks until finishedstats := pinger.Statistics()fmt.Println(stats)// 有回包,就是说明IP是可用的if stats.PacketsRecv >= 1 {return true}return false}

这里是通过回包数量来判断的,也可以通过掉包率来判断。同时,该库提供了Statistics结构体,包含了详细的ICMP信息,如下

type Statistics struct {// PacketsRecv is the number of packets received.PacketsRecv int// PacketsSent is the number of packets sent.PacketsSent int// PacketLoss is the percentage of packets lost.PacketLoss float64// IPAddr is the address of the host being pinged.IPAddr *net.IPAddr// Addr is the string address of the host being pinged.Addr string// Rtts is all of the round-trip times sent via this pinger.Rtts []time.Duration// MinRtt is the minimum round-trip time sent via this pinger.MinRtt time.Duration// MaxRtt is the maximum round-trip time sent via this pinger.MaxRtt time.Duration// AvgRtt is the average round-trip time sent via this pinger.AvgRtt time.Duration// StdDevRtt is the standard deviation of the round-trip times sent via// this pinger.StdDevRtt time.Duration}

更多golang知识请关注PHP中文网golang教程栏目。

更多相关文章

  1. go语言中控制并发数量的方法
  2. PMP项目管理:PMIID与PDU数量速查
  3. 关于PHP http 报文设置 CURLOPT_HTTPHEADER
  4. SharePoint 解决方案:如何获取Library或者List下的Item数量
  5. 如何在数组中存储产品数量
  6. 在Symfony2中使用Doctrine DQL时检索的记录数量限制
  7. 存储过程,参数数量不正确bug?
  8. 在指定的div - js内按id计算div的数量
  9. Bash脚本删除目录中多个文件名末尾的'x'字符数量?

随机推荐

  1. 自动换行
  2. Android 代码改变图片颜色android:tint="
  3. Android中让View匀速旋转
  4. Android 底部导航栏中间凸起、越界显示
  5. Android 默认水波纹的使用和去除
  6. android开发之android:padding和android:
  7. EditText 文字验证
  8. Windows下git下载android source
  9. Android 获取手机卡相关信息
  10. Android:控件布局(相对布局)RelativeLayout(