Proper detection of ephemeral ports on Mac OS (#7539)

Use systemctl to properly detect ephemeral ports on Mac OS (aka darwin) by fetching
systemctl values:
 * net.inet.ip.portrange.first
 * net.inet.ip.portrange.last

This will avoid the message:

`[INFO] freeport: ephemeral port range detection not configured for GOOS="darwin"`

and properly detect the correct port range
This commit is contained in:
Pierre Souchay 2020-03-30 15:13:03 +02:00 committed by GitHub
parent 494faca279
commit 952b60abaa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 1 deletions

View File

@ -0,0 +1,37 @@
//+build darwin
package freeport
import (
"fmt"
"os/exec"
"regexp"
"strconv"
)
const ephemeralPortRangeSysctlFirst = "net.inet.ip.portrange.first"
const ephemeralPortRangeSysctlLast = "net.inet.ip.portrange.last"
var ephemeralPortRangePatt = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s*$`)
func getEphemeralPortRange() (int, int, error) {
cmd := exec.Command("/usr/sbin/sysctl", "-n", ephemeralPortRangeSysctlFirst, ephemeralPortRangeSysctlLast)
out, err := cmd.Output()
if err != nil {
return 0, 0, err
}
val := string(out)
m := ephemeralPortRangePatt.FindStringSubmatch(val)
if m != nil {
min, err1 := strconv.Atoi(m[1])
max, err2 := strconv.Atoi(m[2])
if err1 == nil && err2 == nil {
return min, max, nil
}
}
return 0, 0, fmt.Errorf("unexpected sysctl value %q for keys %q, %q", val, ephemeralPortRangeSysctlFirst, ephemeralPortRangeSysctlLast)
}

View File

@ -0,0 +1,18 @@
//+build darwin
package freeport
import (
"testing"
)
func TestGetEphemeralPortRange(t *testing.T) {
min, max, err := getEphemeralPortRange()
if err != nil {
t.Fatalf("err: %v", err)
}
if min <= 0 || max <= 0 || min > max {
t.Fatalf("unexpected values: min=%d, max=%d", min, max)
}
t.Logf("min=%d, max=%d", min, max)
}

View File

@ -1,4 +1,4 @@
//+build !linux
//+build !linux,!darwin
package freeport