/* The MIT License (MIT) Copyright © 2025 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath wports.go */ package main import ( "net" "os" "runtime" "strconv" "sync" "time" ) const info = ` wports [options...] Which PORTS finds all localhost TCP ports currently in use. The only option available is to show this help message, using any of "-h", "--h", "-help", or "--help", without the quotes. ` const ( // timeout gives plenty of waiting-time to check localhost ports timeout = 500 * time.Millisecond // lastPort = int(^uint16(0)) lastPort = 1<<16 - 1 ) // result values report which ports are being used type result struct { // When is the date/time the port was checked When time.Time // Port is the port number among those being used Port uint16 } func main() { args := os.Args[1:] if len(args) > 0 { switch args[0] { case `-h`, `--h`, `-help`, `--help`: os.Stderr.WriteString(info[1:]) return case `--`: args = args[1:] } } _, err := os.Stdout.WriteString("when\tport\n") if err != nil { return } results := make(chan result) go run(results) // buf is a buffer big enough for any output line var buf [32]byte for r := range results { line := buf[:0] line = r.When.AppendFormat(line, `2006-01-02 15:04:05`) line = append(line, '\t') line = strconv.AppendInt(line, int64(r.Port), 10) line = append(line, '\n') _, err := os.Stdout.Write(line) if err != nil { return } } } type asyncArgs struct { Results chan result // Permissions limits how many ports are being checked at any time, // avoiding using hundreds of megabytes in the process, while still // being done checking all ports in a few seconds Permissions chan struct{} // Tasks is to wait for all tasks to end before quitting the app Tasks *sync.WaitGroup } // run asynchronously dispatches tasks to check all ports func run(results chan result) { var tasks sync.WaitGroup // the number of tasks is always known in advance tasks.Add(lastPort) args := asyncArgs{ Results: results, Permissions: make(chan struct{}, runtime.NumCPU()), Tasks: &tasks, } defer close(args.Results) // allow the main app to end defer close(args.Permissions) // avoid checking port 0, as it's the `anything-available` port for port := 1; port <= lastPort; port++ { // wait until some concurrency-room is available, before proceeding args.Permissions <- struct{}{} go check(uint16(port), args) } // wait for all checks to finish, before closing the `results` channel, // which in turn would quit the whole app right away args.Tasks.Wait() } // check reports on its given TCP port, only if it's being used func check(port uint16, args asyncArgs) { when := time.Now() defer args.Tasks.Done() defer func() { <-args.Permissions }() var buf [24]byte addr := strconv.AppendInt(append(buf[:0], ':'), int64(port), 10) conn, err := net.DialTimeout(`tcp`, string(addr), timeout) if err != nil { return } conn.Close() args.Results <- result{When: when, Port: port} }