1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| package main
import ( "flag" "fmt" "net" "sort" "strconv" "time" )
func worker(ip string, ports chan int, result chan int) { for port := range ports { addr := net.JoinHostPort(ip, strconv.Itoa(port))
conn, err := net.Dial("tcp", addr) if err != nil { result <- 0 continue }
conn.Close() result <- port } }
func main() { var ip string flag.StringVar(&ip, "ip", "127.0.0.1", "input ip for scan(support ipv4/6)") flag.Parse() fmt.Printf("scan (%s) range 1~65535\n", ip)
jobs := make(chan int, 10240) result := make(chan int)
start := time.Now()
var openedPorts []int for p := 0; p < cap(jobs); p++ { go worker(ip, jobs, result) }
go func() { for j := 1; j <= 65535; j++ { jobs <- j } }()
for j := 1; j <= 65535; j++ { r := <-result
if r != 0 { openedPorts = append(openedPorts, r) } }
close(jobs) close(result)
fmt.Println("open ports:") sort.Ints(openedPorts) for _, port := range openedPorts { fmt.Println(port) }
since := time.Since(start) fmt.Printf("time consuming %v", since)
}
|