diff --git a/README.md b/README.md index e22c936..d492263 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/main.go b/main.go new file mode 100644 index 0000000..6b6b71e --- /dev/null +++ b/main.go @@ -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) + } +}