From d82625919e56da7ab72435fb103f2ffeda587e5e Mon Sep 17 00:00:00 2001 From: bo-er <49479987+bo-er@users.noreply.github.com> Date: Thu, 25 Nov 2021 05:38:23 +0800 Subject: [PATCH] Fix bug when /proc/net/dev contains unexpected line (#421) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix bug when /proc/net/dev contains unexpected line Signed-off-by: 吴家榜 <14038@chinasws.com> * modifying netDev.parseLine due to odd interface name Signed-off-by: 吴家榜 <14038@chinasws.com> * adding testing case for net device that has colon in its name Signed-off-by: 吴家榜 <14038@chinasws.com> Co-authored-by: wujiabang Co-authored-by: 吴家榜 <14038@chinasws.com> --- net_dev.go | 8 ++++---- net_dev_test.go | 21 ++++++++++++--------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/net_dev.go b/net_dev.go index 47a710bef..e66208aa0 100644 --- a/net_dev.go +++ b/net_dev.go @@ -87,17 +87,17 @@ func newNetDev(file string) (NetDev, error) { // parseLine parses a single line from the /proc/net/dev file. Header lines // must be filtered prior to calling this method. func (netDev NetDev) parseLine(rawLine string) (*NetDevLine, error) { - parts := strings.SplitN(rawLine, ":", 2) - if len(parts) != 2 { + idx := strings.LastIndex(rawLine, ":") + if idx == -1 { return nil, errors.New("invalid net/dev line, missing colon") } - fields := strings.Fields(strings.TrimSpace(parts[1])) + fields := strings.Fields(strings.TrimSpace(rawLine[idx+1:])) var err error line := &NetDevLine{} // Interface Name - line.Name = strings.TrimSpace(parts[0]) + line.Name = strings.TrimSpace(rawLine[:idx]) if line.Name == "" { return nil, errors.New("invalid net/dev line, empty interface name") } diff --git a/net_dev_test.go b/net_dev_test.go index c26c7b295..fb5390e10 100644 --- a/net_dev_test.go +++ b/net_dev_test.go @@ -14,21 +14,24 @@ package procfs import ( + "fmt" "testing" ) func TestNetDevParseLine(t *testing.T) { - const rawLine = ` eth0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16` - - have, err := NetDev{}.parseLine(rawLine) - if err != nil { - t.Fatal(err) + tc := []string{"eth0", "eth0:1"} + for i := range tc { + rawLine := fmt.Sprintf(` %v: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`, tc[i]) + have, err := NetDev{}.parseLine(rawLine) + if err != nil { + t.Fatal(err) + } + want := NetDevLine{tc[i], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} + if want != *have { + t.Errorf("want %v, have %v", want, have) + } } - want := NetDevLine{"eth0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - if want != *have { - t.Errorf("want %v, have %v", want, have) - } } func TestNetDev(t *testing.T) {