github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/helper/freeport/ephemeral_linux.go (about) 1 //go:build linux 2 // +build linux 3 4 package freeport 5 6 import ( 7 "fmt" 8 "os/exec" 9 "regexp" 10 "strconv" 11 ) 12 13 /* 14 $ sysctl -n net.ipv4.ip_local_port_range 15 32768 60999 16 */ 17 18 const ephemeralPortRangeSysctlKey = "net.ipv4.ip_local_port_range" 19 20 var ephemeralPortRangePatt = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s*$`) 21 22 func getEphemeralPortRange() (int, int, error) { 23 cmd := exec.Command("sysctl", "-n", ephemeralPortRangeSysctlKey) 24 out, err := cmd.Output() 25 if err != nil { 26 return 0, 0, err 27 } 28 29 val := string(out) 30 31 m := ephemeralPortRangePatt.FindStringSubmatch(val) 32 if m != nil { 33 min, err1 := strconv.Atoi(m[1]) 34 max, err2 := strconv.Atoi(m[2]) 35 36 if err1 == nil && err2 == nil { 37 return min, max, nil 38 } 39 } 40 41 return 0, 0, fmt.Errorf("unexpected sysctl value %q for key %q", val, ephemeralPortRangeSysctlKey) 42 }