[Go] Go语言实现的简单网络端口扫描代码 →→→→→进入此内容的聊天室

来自 , 2021-01-09, 写在 Go, 查看 135 次.
URL http://www.code666.cn/view/2fe5a27c
  1. package main
  2.  
  3. import (
  4.         "net"
  5.         "fmt"
  6.         "os"
  7.         "runtime"
  8.         "time"
  9.         "strconv"
  10. )
  11.  
  12. func loop(startport, endport int, inport chan int) {
  13.                 for i := startport; i <= endport; i++{
  14.                         inport <- i
  15.                 }
  16. }
  17.  
  18. func scanner(inport, outport, out chan int, ip net.IP, endport int){
  19.         for{
  20.                 in := <- inport
  21.                 //fmt.Println(in)
  22.                 tcpaddr := &net.TCPAddr{ip,in}
  23.                 conn, err := net.DialTCP("tcp", nil, tcpaddr)
  24.                 if err != nil {
  25.                         outport <- 0
  26.                 }else{
  27.                         outport <- in
  28.                 }
  29.                 conn.Close()
  30.                 if in == endport{
  31.                         out <- in
  32.                 }
  33.         }
  34. }
  35.  
  36. func main() {
  37.         starttime := time.Now().Unix()
  38.         runtime.GOMAXPROCS(4)
  39.         inport := make(chan int)
  40.         outport := make(chan int)
  41.         out := make(chan int)
  42.         collect := []int{}
  43.         if len(os.Args) != 4 {
  44.                 fmt.Println("Usage: scanner.exe IP startport endport")
  45.                 fmt.Println("Endport must be larger than startport")
  46.                 os.Exit(0)
  47.         }
  48.         ip := net.ParseIP(os.Args[1])
  49.         if(os.Args[3] < os.Args[2]) {
  50.                 fmt.Println("Usage: scanner IP startport endport")
  51.                 fmt.Println("Endport must be larger than startport")
  52.                 os.Exit(0)
  53.         }
  54.         startport, _:= strconv.Atoi(os.Args[2])
  55.         endport, _ := strconv.Atoi(os.Args[3])
  56.         go loop(startport, endport, inport)
  57.         for{
  58.                 select {
  59.                         case <-out:
  60.                                 fmt.Println(collect)
  61.                                 endtime := time.Now().Unix()
  62.                                 fmt.Println("The scan process has spent ",endtime-starttime,"second")
  63.                                 os.Exit(0)
  64.                         default:
  65.                                 go scanner(inport, outport, out, ip, endport)
  66.                                
  67.                                 port := <- outport
  68.                                
  69.                                 if port != 0{
  70.                                         collect = append(collect, port)
  71.                                 }
  72.                 }              
  73.         }
  74. }
  75.  
  76. //go/4359

回复 "Go语言实现的简单网络端口扫描代码"

这儿你可以回复上面这条便签

captcha