diff --git a/pkg/netstat/netstat_util.go b/pkg/netstat/netstat_util.go index a224db4d1..63ea79457 100644 --- a/pkg/netstat/netstat_util.go +++ b/pkg/netstat/netstat_util.go @@ -186,7 +186,7 @@ func getProcName(s []byte) string { return "" } j := bytes.LastIndex(s, []byte(")")) - if i < 0 { + if j < 0 { return "" } if i > j { diff --git a/pkg/netstat/netstat_util_test.go b/pkg/netstat/netstat_util_test.go index fddba09b1..a68e9f6ea 100644 --- a/pkg/netstat/netstat_util_test.go +++ b/pkg/netstat/netstat_util_test.go @@ -92,3 +92,24 @@ func (s *NetstatUtilTestSuite) TestDoNetstat_PropagatesParseError() { assert.Error(s.T(), err, "parser errors must propagate") } + +func (s *NetstatUtilTestSuite) TestGetProcName() { + tests := []struct { + name string + input string + want string + }{ + {"name in parens", "1234 (comm-name) stuff", "comm-name"}, + {"no opening paren", "comm-name", ""}, + {"no closing paren", "1234 (comm-name", ""}, + {"reversed parens", ")comm-name(", ""}, + {"empty name", "1234 ()", ""}, + {"name with parens inside", "1234 (a (b) c)", "a (b) c"}, + } + + for _, tt := range tests { + s.Run(tt.name, func() { + assert.Equal(s.T(), tt.want, getProcName([]byte(tt.input))) + }) + } +}