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
| package main
import ( "flag" "fmt" "net" "sync" "time" )
func isOpen(host string, port int, timeout time.Duration) bool { time.Sleep(time.Millisecond * 1) conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", host, port), timeout) if err == nil { _ = conn.Close() return true } return false } func main() { hostname := flag.String("hostname", "baidu.com", "hostname to test") startPort := flag.Int("startPort", 80, "the port on which the scanning starts") endPort := flag.Int("end-port", 100, "the port from which the scanning ends") timeout := flag.Duration("timeout", time.Millisecond*200, "timeout") flag.Parse()
ports := []int{}
wg := &sync.WaitGroup{} mutex := &sync.Mutex{} for port := *startPort; port <= *endPort; port++ { wg.Add(1) go func(p int) { opened := isOpen(*hostname, p, *timeout) if opened { mutex.Lock() ports = append(ports, p) mutex.Unlock() } wg.Done() }(port) } wg.Wait() fmt.Printf("opened.ports:%v\n", ports) }
|