Skip to content

Instantly share code, notes, and snippets.

@Vostbur
Created March 11, 2023 18:34
Show Gist options
  • Save Vostbur/92328cfd9cb56beb4c4f21286a44d7fb to your computer and use it in GitHub Desktop.
Save Vostbur/92328cfd9cb56beb4c4f21286a44d7fb to your computer and use it in GitHub Desktop.
TCP scanner from Black Hat Go book
package main
import (
"fmt"
"net"
"sort"
)
func worker(ports, results chan int) {
for p := range ports {
address := fmt.Sprintf("scanme.nmap.org:%d", p)
conn, err := net.Dial("tcp", address)
if err != nil {
results <- 0
continue
}
conn.Close()
results <- p
}
}
func main() {
ports := make(chan int, 100)
results := make(chan int)
var openports []int
for i := 0; i < cap(ports); i++ {
go worker(ports, results)
}
go func() {
for i := 1; i <= 1024; i++ {
ports <- i
}
}()
for i := 0; i < 1024; 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment