File: wports.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2025 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath wports.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "net"
  36     "os"
  37     "runtime"
  38     "strconv"
  39     "sync"
  40     "time"
  41 )
  42 
  43 const info = `
  44 wports [options...]
  45 
  46 Which PORTS finds all localhost TCP ports currently in use.
  47 
  48 The only option available is to show this help message, using any of
  49 "-h", "--h", "-help", or "--help", without the quotes.
  50 `
  51 
  52 const (
  53     // timeout gives plenty of waiting-time to check localhost ports
  54     timeout = 500 * time.Millisecond
  55 
  56     // lastPort = int(^uint16(0))
  57 
  58     lastPort = 1<<16 - 1
  59 )
  60 
  61 // result values report which ports are being used
  62 type result struct {
  63     // When is the date/time the port was checked
  64     When time.Time
  65 
  66     // Port is the port number among those being used
  67     Port uint16
  68 }
  69 
  70 func main() {
  71     args := os.Args[1:]
  72 
  73     if len(args) > 0 {
  74         switch args[0] {
  75         case `-h`, `--h`, `-help`, `--help`:
  76             os.Stderr.WriteString(info[1:])
  77             return
  78 
  79         case `--`:
  80             args = args[1:]
  81         }
  82     }
  83 
  84     _, err := os.Stdout.WriteString("when\tport\n")
  85     if err != nil {
  86         return
  87     }
  88 
  89     results := make(chan result)
  90     go run(results)
  91 
  92     // buf is a buffer big enough for any output line
  93     var buf [32]byte
  94 
  95     for r := range results {
  96         line := buf[:0]
  97         line = r.When.AppendFormat(line, `2006-01-02 15:04:05`)
  98         line = append(line, '\t')
  99         line = strconv.AppendInt(line, int64(r.Port), 10)
 100         line = append(line, '\n')
 101 
 102         _, err := os.Stdout.Write(line)
 103         if err != nil {
 104             return
 105         }
 106     }
 107 }
 108 
 109 type asyncArgs struct {
 110     Results chan result
 111 
 112     // Permissions limits how many ports are being checked at any time,
 113     // avoiding using hundreds of megabytes in the process, while still
 114     // being done checking all ports in a few seconds
 115     Permissions chan struct{}
 116 
 117     // Tasks is to wait for all tasks to end before quitting the app
 118     Tasks *sync.WaitGroup
 119 }
 120 
 121 // run asynchronously dispatches tasks to check all ports
 122 func run(results chan result) {
 123     var tasks sync.WaitGroup
 124     // the number of tasks is always known in advance
 125     tasks.Add(lastPort)
 126 
 127     args := asyncArgs{
 128         Results:     results,
 129         Permissions: make(chan struct{}, runtime.NumCPU()),
 130         Tasks:       &tasks,
 131     }
 132 
 133     defer close(args.Results) // allow the main app to end
 134     defer close(args.Permissions)
 135 
 136     // avoid checking port 0, as it's the `anything-available` port
 137     for port := 1; port <= lastPort; port++ {
 138         // wait until some concurrency-room is available, before proceeding
 139         args.Permissions <- struct{}{}
 140         go check(uint16(port), args)
 141     }
 142 
 143     // wait for all checks to finish, before closing the `results` channel,
 144     // which in turn would quit the whole app right away
 145     args.Tasks.Wait()
 146 }
 147 
 148 // check reports on its given TCP port, only if it's being used
 149 func check(port uint16, args asyncArgs) {
 150     when := time.Now()
 151     defer args.Tasks.Done()
 152     defer func() { <-args.Permissions }()
 153 
 154     var buf [24]byte
 155     addr := strconv.AppendInt(append(buf[:0], ':'), int64(port), 10)
 156     conn, err := net.DialTimeout(`tcp`, string(addr), timeout)
 157     if err != nil {
 158         return
 159     }
 160     conn.Close()
 161 
 162     args.Results <- result{When: when, Port: port}
 163 }