douyou9923 2018-09-10 12:48
浏览 66
已采纳

如何从go-ping存储库中将net类型变量转换并附加到Golang中的字符串切片中?

This is the entire code, not much different from the one you can find on the git repo page.

package main
import (
    "fmt"
    "github.com/go-ping"
    "time"
)

var stats = [][]string{nil}

func pinging(domain string, interval int, unit string, exit int) {

current_time:= time.Now().Local()
current_time.Format("02-01-2000")

switch unit {

case "ms":
    interval *= 1
case "sec":
    interval *= 1000
case "min":
    interval *= 6000

}

pinger, err := ping.NewPinger(domain)
if err != nil {
    panic(err)
}

// interval between ping
pinger.Interval=time.Millisecond*time.Duration(interval)

//number of total pings
pinger.Count=exit

pinger.OnRecv = func(pkt *ping.Packet) {
    fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v
",
        pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
}
pinger.OnFinish = func(stats *ping.Statistics) {
    fmt.Printf("
--- %s ping statistics ---
", stats.Addr)
    fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss
",
        stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
    fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v
",
        stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
}

fmt.Printf("PING %s (%s):
", pinger.Addr(), pinger.IPAddr())
pinger.Run()

}

I need to convert and append to a slice of string these variables pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, which are type *net from this repo https://github.com/sparrc/go-ping .

I need to do so because after that I'll print everything to a .csv How could I do that?

  • 写回答

1条回答 默认 最新

  • dongxing8009 2018-09-10 13:00
    关注

    Use fmt.Sprintf with your example code:

    var s []string
    s = append(s, fmt.Sprintf("%d", pkt.Nbytes)
    s = append(s, fmt.Sprintf("%s", pkt.IPAddr)
    s = append(s, fmt.Sprintf("%d", pkt.Seq)
    s = append(s, fmt.Sprintf("%v", pkt.Rtt)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?