@@ -46,8 +46,10 @@ func GetSystemStats() (*common.SystemStatsResponse, error) {
4646
4747// getBandwidthSpeed returns the aggregate incoming (rx) and outgoing (tx)
4848// bandwidth in bytes per second, sampled over a 1‑second interval.
49+ // Loopback interface (lo) is excluded from the calculation.
4950func getBandwidthSpeed () (uint64 , uint64 , error ) {
50- // 1) First snapshot
51+ // 1) First snapshot with timestamp
52+ start := time .Now ()
5153 first , err := net .IOCounters (true )
5254 if err != nil {
5355 return 0 , 0 , err
@@ -56,27 +58,48 @@ func getBandwidthSpeed() (uint64, uint64, error) {
5658 // 2) Wait one second
5759 time .Sleep (1 * time .Second )
5860
59- // 3) Second snapshot
61+ // 3) Second snapshot with timestamp
6062 second , err := net .IOCounters (true )
6163 if err != nil {
6264 return 0 , 0 , err
6365 }
66+ end := time .Now ()
6467
65- // 4) Compute deltas and sum across all interfaces
66- // Build a map from interface name → first snapshot
68+ // 4) Calculate actual elapsed time (not assumed 1 second)
69+ actualDuration := end .Sub (start ).Seconds ()
70+ if actualDuration == 0 {
71+ return 0 , 0 , nil // avoid division by zero
72+ }
73+
74+ // 5) Build a map from interface name → first snapshot
75+ // Skip loopback interface
6776 prev := make (map [string ]net.IOCountersStat , len (first ))
6877 for _ , c := range first {
78+ // Skip loopback interface
79+ if c .Name == "lo" {
80+ continue
81+ }
6982 prev [c .Name ] = c
7083 }
7184
72- var totalRx , totalTx uint64
85+ // 6) Compute deltas and sum across all interfaces
86+ // Skip loopback interface
87+ var totalRxBytes , totalTxBytes uint64
7388 for _ , c := range second {
89+ // Skip loopback interface
90+ if c .Name == "lo" {
91+ continue
92+ }
7493 if p , ok := prev [c .Name ]; ok {
75- totalRx += c .BytesRecv - p .BytesRecv
76- totalTx += c .BytesSent - p .BytesSent
94+ totalRxBytes += c .BytesRecv - p .BytesRecv
95+ totalTxBytes += c .BytesSent - p .BytesSent
7796 }
7897 }
7998
80- // 5) Return the totals
81- return totalRx , totalTx , nil
99+ // 7) Convert bytes to bytes per second using ACTUAL measured time
100+ rxPerSecond := uint64 (float64 (totalRxBytes ) / actualDuration )
101+ txPerSecond := uint64 (float64 (totalTxBytes ) / actualDuration )
102+
103+ // 8) Return the calculated rates (bytes per second)
104+ return rxPerSecond , txPerSecond , nil
82105}
0 commit comments