Add initial code

This commit is contained in:
Dave Gallant
2020-02-02 00:56:54 -05:00
parent 8ee2e682d4
commit 2a98b732da
2 changed files with 66 additions and 0 deletions

View File

@@ -1 +1,10 @@
# tcp-port-scanner
To do a port scan on a host, provide the host's domain name or ip.
```shell
go run main.go --host 'localhost'
```
This code is based upon the examples in:
[Black Hat Go](https://nostarch.com/blackhatgo)

57
main.go Normal file
View File

@@ -0,0 +1,57 @@
package main
import (
"flag"
"fmt"
"net"
"sort"
)
var hostname string
func init() {
flag.StringVar(&hostname, "host", "", "the host to be scanned (i.e. localhost)")
}
func worker(ports, results chan int) {
for p := range ports {
address := fmt.Sprintf("%s:%d", hostname, p)
conn, err := net.Dial("tcp", address)
if err != nil {
results <- 0
continue
}
conn.Close()
results <- p
}
}
func main() {
ports := make(chan int, 1000)
results := make(chan int)
var openports []int
for i := 0; i < cap(ports); i++ {
go worker(ports, results)
}
go func() {
for i := 1; i <= 65535; i++ {
ports <- i
}
}()
for i := 0; i < 65535; i++ {
port := <-results
if port != 0 {
openports = append(openports, port)
}
}
close(ports)
close(results)
sort.Ints(openports)
for _, port := range openports {
fmt.Printf("%d open\n", port)
}
}