File: wports.go 1 /* 2 The MIT License (MIT) 3 4 Copyright (c) 2026 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 currently 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 network-port number checked 67 Port int 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.Stdout.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 // run asynchronously dispatches tasks to check all ports 110 func run(results chan<- result) { 111 defer close(results) // allow the main app to end 112 113 var tasks sync.WaitGroup 114 // the number of tasks is always known in advance 115 tasks.Add(lastPort) 116 117 // permissions is buffered to limit concurrency to the core-count 118 permissions := make(chan struct{}, runtime.NumCPU()) 119 defer close(permissions) 120 121 // avoid checking port 0, as it's the `anything-available` port 122 for port := 1; port <= lastPort; port++ { 123 // wait until some concurrency-room is available, before proceeding 124 permissions <- struct{}{} 125 go check(port, &tasks, permissions, results) 126 } 127 128 // wait for all checks to finish, before closing the `results` channel, 129 // which in turn would quit the whole app right away 130 tasks.Wait() 131 } 132 133 // check figures out if the TCP port given is being used 134 func check(port int, tasks *sync.WaitGroup, turn <-chan struct{}, res chan<- result) { 135 when := time.Now() 136 defer tasks.Done() 137 138 var buf [24]byte 139 addr := strconv.AppendInt(append(buf[:0], ':'), int64(port), 10) 140 conn, err := net.DialTimeout(`tcp`, string(addr), timeout) 141 if err != nil { 142 <-turn 143 return 144 } 145 conn.Close() 146 147 <-turn 148 // only report ports being used 149 res <- result{When: when, Port: port} 150 }