Skip to content

Commit

Permalink
Check that port is not in use before binding port on server startup.
Browse files Browse the repository at this point in the history
  • Loading branch information
nicktobey committed Jun 16, 2023
1 parent 8a5b9ac commit 6a17104
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ package server

import (
"errors"
"fmt"
"net"
"time"

"github.com/dolthub/vitess/go/mysql"
Expand Down Expand Up @@ -97,6 +99,16 @@ func NewValidatingServer(
return newServerFromHandler(cfg, e, sm, handler)
}

func portInUse(hostPort string) bool {
timeout := time.Second
conn, _ := net.DialTimeout("tcp", hostPort, timeout)
if conn != nil {
defer conn.Close()
return true
}
return false
}

func newServerFromHandler(cfg Config, e *sqle.Engine, sm *SessionManager, handler mysql.Handler) (*Server, error) {
if cfg.ConnReadTimeout < 0 {
cfg.ConnReadTimeout = 0
Expand All @@ -109,6 +121,11 @@ func newServerFromHandler(cfg Config, e *sqle.Engine, sm *SessionManager, handle
}

var unixSocketInUse error

if portInUse(cfg.Address) {
unixSocketInUse = fmt.Errorf("Port %s already in use.", cfg.Address)
}

l, err := NewListener(cfg.Protocol, cfg.Address, cfg.Socket)
if err != nil {
if errors.Is(err, UnixSocketInUseError) {
Expand Down

0 comments on commit 6a17104

Please sign in to comment.