getBandwidthSpeed returns the aggregate incoming (rx) and outgoing (tx) bandwidth in bytes per second, sampled over a 1-second interval. Loopback interface (lo) is excluded from the calculation.
()
| 48 | // bandwidth in bytes per second, sampled over a 1-second interval. |
| 49 | // Loopback interface (lo) is excluded from the calculation. |
| 50 | func getBandwidthSpeed() (uint64, uint64, error) { |
| 51 | first, err := net.IOCounters(true) |
| 52 | if err != nil { |
| 53 | return 0, 0, err |
| 54 | } |
| 55 | |
| 56 | time.Sleep(1 * time.Second) |
| 57 | |
| 58 | second, err := net.IOCounters(true) |
| 59 | if err != nil { |
| 60 | return 0, 0, err |
| 61 | } |
| 62 | |
| 63 | prev := make(map[string]net.IOCountersStat, len(first)) |
| 64 | for _, c := range first { |
| 65 | if c.Name == "lo" { |
| 66 | continue |
| 67 | } |
| 68 | prev[c.Name] = c |
| 69 | } |
| 70 | |
| 71 | var totalRxBytes, totalTxBytes uint64 |
| 72 | for _, c := range second { |
| 73 | if c.Name == "lo" { |
| 74 | continue |
| 75 | } |
| 76 | if p, ok := prev[c.Name]; ok { |
| 77 | totalRxBytes += c.BytesRecv - p.BytesRecv |
| 78 | totalTxBytes += c.BytesSent - p.BytesSent |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return totalRxBytes, totalTxBytes, nil |
| 83 | } |