Skip to content

Commit

Permalink
Add api/utils/net.IsPortInRange
Browse files Browse the repository at this point in the history
  • Loading branch information
ravicious committed Nov 15, 2024
1 parent 0be87b9 commit 47a9038
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
11 changes: 11 additions & 0 deletions api/utils/net/ports.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,14 @@ func ValidatePortRange(port, endPort int) error {

return nil
}

// IsPortInRange checks if targetPort is between port and endPort (inclusive). If endPort is zero,
// it checks if targetPort equals port. It assumes that the provided port range is valid (see
// [ValidatePortRange]).
func IsPortInRange(port, endPort, targetPort int) bool {
if endPort == 0 {
return targetPort == port
}

return targetPort >= port && targetPort <= endPort
}
73 changes: 73 additions & 0 deletions api/utils/net/ports_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,79 @@ func TestValidatePortRange(t *testing.T) {
}
}

func TestIsPortInRange(t *testing.T) {
tests := []struct {
name string
port int
endPort int
targetPort int
check require.BoolAssertionFunc
}{
{
name: "within single port range",
port: 1337,
endPort: 0,
targetPort: 1337,
check: require.True,
},
{
name: "within port range",
port: 1337,
endPort: 3456,
targetPort: 2550,
check: require.True,
},
{
name: "equal to range start",
port: 1337,
endPort: 3456,
targetPort: 1337,
check: require.True,
},
{
name: "equal to range end",
port: 1337,
endPort: 3456,
targetPort: 3456,
check: require.True,
},
{
name: "outside of single port range",
port: 1337,
endPort: 0,
targetPort: 7331,
check: require.False,
},
{
name: "equal to end of single port range",
port: 1337,
endPort: 0,
targetPort: 0,
check: require.False,
},
{
name: "smaller than range start",
port: 1337,
endPort: 3456,
targetPort: 42,
check: require.False,
},
{
name: "bigger than range end",
port: 1337,
endPort: 3456,
targetPort: 7331,
check: require.False,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.check(t, IsPortInRange(tt.port, tt.endPort, tt.targetPort), "compared %d against %d-%d", tt.targetPort, tt.port, tt.endPort)
})
}
}

func badParameterError(t require.TestingT, err error, msgAndArgs ...interface{}) {
require.True(t, trace.IsBadParameter(err), "expected bad parameter error, got %+v", err)
}
Expand Down

0 comments on commit 47a9038

Please sign in to comment.