type NetworkInterface struct {
Name string `json:"name"`
BytesSent uint64 `json:"bytes_sent"`
BytesRecv uint64 `json:"bytes_recv"`
PacketsSent uint64 `json:"packets_sent"`
PacketsRecv uint64 `json:"packets_recv"`
ErrorsIn uint64 `json:"errors_in"`
ErrorsOut uint64 `json:"errors_out"`
DropsIn uint64 `json:"drops_in"`
DropsOut uint64 `json:"drops_out"`
}
type NetworkInfo struct {
Interfaces []NetworkInterface `json:"interfaces"`
ConnectionCount int `json:"connection_count"`
TotalBytesSent uint64 `json:"total_bytes_sent"`
TotalBytesRecv uint64 `json:"total_bytes_recv"`
}
func CollectNetworkInfoWithContext(ctx context.Context) (NetworkInfo, error) {
// Get network interface statistics
ioCounters, err := net.IOCountersWithContext(ctx, true)
if err != nil {
return NetworkInfo{}, NewSystemError("network_collection", "failed to get network info", err)
}
interfaces := make([]NetworkInterface, 0, len(ioCounters))
var totalSent, totalRecv uint64
for _, io := range ioCounters {
interfaces = append(interfaces, NetworkInterface{
Name: io.Name,
BytesSent: io.BytesSent,
BytesRecv: io.BytesRecv,
PacketsSent: io.PacketsSent,
PacketsRecv: io.PacketsRecv,
ErrorsIn: io.Errin,
ErrorsOut: io.Errout,
DropsIn: io.Dropin,
DropsOut: io.Dropout,
})
totalSent += io.BytesSent
totalRecv += io.BytesRecv
}
// Get connection count
connections, _ := net.ConnectionsWithContext(ctx, "all")
return NetworkInfo{
Interfaces: interfaces,
ConnectionCount: len(connections),
TotalBytesSent: totalSent,
TotalBytesRecv: totalRecv,
}, nil
}