github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/helper/freeport/ephemeral_darwin.go (about)

     1  //go:build darwin
     2  // +build darwin
     3  
     4  package freeport
     5  
     6  import (
     7  	"fmt"
     8  	"os/exec"
     9  	"regexp"
    10  	"strconv"
    11  )
    12  
    13  /*
    14  $ sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
    15  net.inet.ip.portrange.first: 49152
    16  net.inet.ip.portrange.last: 65535
    17  */
    18  
    19  const (
    20  	ephPortFirst = "net.inet.ip.portrange.first"
    21  	ephPortLast  = "net.inet.ip.portrange.last"
    22  	command      = "sysctl"
    23  )
    24  
    25  var ephPortRe = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s*$`)
    26  
    27  func getEphemeralPortRange() (int, int, error) {
    28  	cmd := exec.Command(command, "-n", ephPortFirst, ephPortLast)
    29  	out, err := cmd.Output()
    30  	if err != nil {
    31  		return 0, 0, err
    32  	}
    33  
    34  	val := string(out)
    35  
    36  	m := ephPortRe.FindStringSubmatch(val)
    37  	if m != nil {
    38  		min, err1 := strconv.Atoi(m[1])
    39  		max, err2 := strconv.Atoi(m[2])
    40  
    41  		if err1 == nil && err2 == nil {
    42  			return min, max, nil
    43  		}
    44  	}
    45  
    46  	return 0, 0, fmt.Errorf("unexpected sysctl value %q for keys %q %q", val, ephPortFirst, ephPortLast)
    47  }