github.com/dolthub/go-mysql-server@v0.18.0/server/net_listener_unix.go (about)

     1  //go:build !windows
     2  
     3  package server
     4  
     5  import (
     6  	"context"
     7  	"net"
     8  	"syscall"
     9  
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  // Very rarely in our CI, the server fails to bind to the port with the error: "port already in use."
    14  // This is odd because the server already confirms that the port is not in use before connecting.
    15  // Using the SO_REUSEADDR and SO_REUSEPORT options prevents this spurious failure.
    16  // This is safe to do because we have already checked that the
    17  func newNetListener(protocol, address string) (net.Listener, error) {
    18  	lc := net.ListenConfig{
    19  		Control: func(network, address string, c syscall.RawConn) error {
    20  			var socketErr error
    21  			err := c.Control(func(fd uintptr) {
    22  				err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
    23  				if err != nil {
    24  					socketErr = err
    25  				}
    26  
    27  				err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
    28  				if err != nil {
    29  					socketErr = err
    30  				}
    31  			})
    32  			if err != nil {
    33  				return err
    34  			}
    35  			return socketErr
    36  		},
    37  	}
    38  	return lc.Listen(context.Background(), protocol, address)
    39  }