github.com/ddev/ddev@v1.23.2-0.20240519125000-d824ffe36ff3/pkg/netutil/netutil.go (about)

     1  package netutil
     2  
     3  import (
     4  	"github.com/ddev/ddev/pkg/dockerutil"
     5  	"github.com/ddev/ddev/pkg/util"
     6  	"net"
     7  	"os"
     8  	"syscall"
     9  )
    10  
    11  // IsPortActive checks to see if the given port on Docker IP is answering.
    12  func IsPortActive(port string) bool {
    13  	dockerIP, err := dockerutil.GetDockerIP()
    14  	if err != nil {
    15  		util.Warning("Failed to get Docker IP address: %v", err)
    16  		return false
    17  	}
    18  
    19  	conn, err := net.Dial("tcp", dockerIP+":"+port)
    20  
    21  	// If we were able to connect, something is listening on the port.
    22  	if err == nil {
    23  		_ = conn.Close()
    24  		return true
    25  	}
    26  	// If we get ECONNREFUSED the port is not active.
    27  	oe, ok := err.(*net.OpError)
    28  	if ok {
    29  		syscallErr, ok := oe.Err.(*os.SyscallError)
    30  
    31  		// On Windows, WSAECONNREFUSED (10061) results instead of ECONNREFUSED. And golang doesn't seem to have it.
    32  		var WSAECONNREFUSED syscall.Errno = 10061
    33  
    34  		if ok && (syscallErr.Err == syscall.ECONNREFUSED || syscallErr.Err == WSAECONNREFUSED) {
    35  			return false
    36  		}
    37  	}
    38  	// Otherwise, hmm, something else happened. It's not a fatal or anything.
    39  	util.Warning("Unable to properly check port status: %v", oe)
    40  	return false
    41  }