net_linux.go 2.0 KB
Newer Older
1 2
// +build linux

S
Shirou WAKAYAMA 已提交
3
package net
4 5

import (
6
	"strconv"
7
	"strings"
W
WAKAYAMA shirou 已提交
8

9
	"github.com/shirou/gopsutil/internal/common"
10 11
)

12 13 14 15 16
// NetIOCounters returnes network I/O statistics for every network
// interface installed on the system.  If pernic argument is false,
// return only sum of all information (which name is 'all'). If true,
// every network interface installed on the system is returned
// separately.
17
func NetIOCounters(pernic bool) ([]NetIOCountersStat, error) {
18
	filename := common.HostProc("net/dev")
W
WAKAYAMA shirou 已提交
19
	lines, err := common.ReadLines(filename)
20
	if err != nil {
21
		return nil, err
22 23 24 25
	}

	statlen := len(lines) - 1

S
Shirou WAKAYAMA 已提交
26
	ret := make([]NetIOCountersStat, 0, statlen)
27 28

	for _, line := range lines[2:] {
29 30 31 32 33 34
		parts := strings.SplitN(line, ":", 2)
		if len(parts) != 2 {
			continue
		}
		interfaceName := strings.TrimSpace(parts[0])
		if interfaceName == "" {
35 36
			continue
		}
37

38 39
		fields := strings.Fields(strings.TrimSpace(parts[1]))
		bytesRecv, err := strconv.ParseUint(fields[0], 10, 64)
40 41 42
		if err != nil {
			return ret, err
		}
43
		packetsRecv, err := strconv.ParseUint(fields[1], 10, 64)
44 45 46
		if err != nil {
			return ret, err
		}
47
		errIn, err := strconv.ParseUint(fields[2], 10, 64)
48 49 50
		if err != nil {
			return ret, err
		}
51
		dropIn, err := strconv.ParseUint(fields[3], 10, 64)
52 53 54
		if err != nil {
			return ret, err
		}
55
		bytesSent, err := strconv.ParseUint(fields[8], 10, 64)
56 57 58
		if err != nil {
			return ret, err
		}
59
		packetsSent, err := strconv.ParseUint(fields[9], 10, 64)
60 61 62
		if err != nil {
			return ret, err
		}
63
		errOut, err := strconv.ParseUint(fields[10], 10, 64)
64 65 66
		if err != nil {
			return ret, err
		}
67
		dropOut, err := strconv.ParseUint(fields[13], 10, 64)
68 69 70 71
		if err != nil {
			return ret, err
		}

S
Shirou WAKAYAMA 已提交
72
		nic := NetIOCountersStat{
73
			Name:        interfaceName,
74 75 76 77 78 79 80 81
			BytesRecv:   bytesRecv,
			PacketsRecv: packetsRecv,
			Errin:       errIn,
			Dropin:      dropIn,
			BytesSent:   bytesSent,
			PacketsSent: packetsSent,
			Errout:      errOut,
			Dropout:     dropOut,
82 83 84
		}
		ret = append(ret, nic)
	}
85 86 87 88 89

	if pernic == false {
		return getNetIOCountersAll(ret)
	}

90 91
	return ret, nil
}