Skip to content

Commit 081c329

Browse files
bo-er吴家榜
and
吴家榜
authored
Fix bug when /proc/net/dev contains unexpected line (#421)
* fix bug when /proc/net/dev contains unexpected line Signed-off-by: 吴家榜 <[email protected]> * modifying netDev.parseLine due to odd interface name Signed-off-by: 吴家榜 <[email protected]> * adding testing case for net device that has colon in its name Signed-off-by: 吴家榜 <[email protected]> Co-authored-by: wujiabang <[email protected]> Co-authored-by: 吴家榜 <[email protected]>
1 parent 4f613c6 commit 081c329

File tree

2 files changed

+16
-13
lines changed

2 files changed

+16
-13
lines changed

net_dev.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -87,17 +87,17 @@ func newNetDev(file string) (NetDev, error) {
8787
// parseLine parses a single line from the /proc/net/dev file. Header lines
8888
// must be filtered prior to calling this method.
8989
func (netDev NetDev) parseLine(rawLine string) (*NetDevLine, error) {
90-
parts := strings.SplitN(rawLine, ":", 2)
91-
if len(parts) != 2 {
90+
idx := strings.LastIndex(rawLine, ":")
91+
if idx == -1 {
9292
return nil, errors.New("invalid net/dev line, missing colon")
9393
}
94-
fields := strings.Fields(strings.TrimSpace(parts[1]))
94+
fields := strings.Fields(strings.TrimSpace(rawLine[idx+1:]))
9595

9696
var err error
9797
line := &NetDevLine{}
9898

9999
// Interface Name
100-
line.Name = strings.TrimSpace(parts[0])
100+
line.Name = strings.TrimSpace(rawLine[:idx])
101101
if line.Name == "" {
102102
return nil, errors.New("invalid net/dev line, empty interface name")
103103
}

net_dev_test.go

+12-9
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,24 @@
1414
package procfs
1515

1616
import (
17+
"fmt"
1718
"testing"
1819
)
1920

2021
func TestNetDevParseLine(t *testing.T) {
21-
const rawLine = ` eth0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`
22-
23-
have, err := NetDev{}.parseLine(rawLine)
24-
if err != nil {
25-
t.Fatal(err)
22+
tc := []string{"eth0", "eth0:1"}
23+
for i := range tc {
24+
rawLine := fmt.Sprintf(` %v: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`, tc[i])
25+
have, err := NetDev{}.parseLine(rawLine)
26+
if err != nil {
27+
t.Fatal(err)
28+
}
29+
want := NetDevLine{tc[i], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
30+
if want != *have {
31+
t.Errorf("want %v, have %v", want, have)
32+
}
2633
}
2734

28-
want := NetDevLine{"eth0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
29-
if want != *have {
30-
t.Errorf("want %v, have %v", want, have)
31-
}
3235
}
3336

3437
func TestNetDev(t *testing.T) {

0 commit comments

Comments
 (0)