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

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
package main
 
import (
    "net"
    "fmt"
    "os"
    "runtime"
    "time"
    "strconv"
)
 
func loop(startport, endport int, inport chan int) {
        for i := startport; i <= endport; i++{
            inport <- i
        }
}
 
func scanner(inport, outport, out chan int, ip net.IP, endport int){
    for{
        in := <- inport
        //fmt.Println(in)
        tcpaddr := &net.TCPAddr{ip,in}
        conn, err := net.DialTCP("tcp", nil, tcpaddr)
        if err != nil {
            outport <- 0
        }else{
            outport <- in
        }
        conn.Close()
        if in == endport{
            out <- in
        }
    }
}
 
func main() {
    starttime := time.Now().Unix()
    runtime.GOMAXPROCS(4)
    inport := make(chan int)
    outport := make(chan int)
    out := make(chan int)
    collect := []int{}
    if len(os.Args) != 4 {
        fmt.Println("Usage: scanner.exe IP startport endport")
        fmt.Println("Endport must be larger than startport")
        os.Exit(0)
    }
    ip := net.ParseIP(os.Args[1])
    if(os.Args[3] < os.Args[2]) {
        fmt.Println("Usage: scanner IP startport endport")
        fmt.Println("Endport must be larger than startport")
        os.Exit(0)
    }
    startport, _:= strconv.Atoi(os.Args[2])
    endport, _ := strconv.Atoi(os.Args[3])
    go loop(startport, endport, inport)
    for{
        select {
            case <-out:
                fmt.Println(collect)
                endtime := time.Now().Unix()
                fmt.Println("The scan process has spent ",endtime-starttime,"second")
                os.Exit(0)
            default:
                go scanner(inport, outport, out, ip, endport)
                 
                port := <- outport
                 
                if port != 0{
                    collect = append(collect, port)
                }
        }      
    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Go语言实现选择法排序

下一篇:Go语言通过smtp发送邮件的示例代码