TCP扫描端口

1.非并发

package main

import (
    "fmt"
    "net"
)

func main() {
    for i := 21; i < 120; i++ {
        address := fmt.Sprintf("192.168.90.1:%d", i)
        conn, err := net.Dial("tcp", address)
        if err != nil {
            fmt.Printf("%s 关闭了 \n", address)
            continue
        }
        conn.Close()
        fmt.Printf("%s 打开了!!!\n", address)
    }
}

结果:

 

 

 

2.并发

package main

import (
    "fmt"
    "net"
    "sync"
    "time"
)

func main() {
    start := time.Now()
    var wg sync.WaitGroup //计数器
    for i := 21; i < 120; i++ {
        wg.Add(1) //加一
        //每次循环创建一个 go func
        go func(j int) {
            defer wg.Done() //减1
            address := fmt.Sprintf("192.168.90.1:%d", j)
            conn, err := net.Dial("tcp", address)
            if err != nil {
                fmt.Printf("%s 关闭了 \n", address)
                return
            }
            conn.Close()
            fmt.Printf("%s 打开了!!!\n", address)
        }(i)
    }
    wg.Wait()                         //直到wg计数器位0放行
    elapse := time.Since(start) / 1e9 //运行时长
    fmt.Printf("\n %d second:", elapse)
}

结果:

 

感谢:https://www.bilibili.com/video/BV13K4y1a7dt?p=3

 

posted @ 2021-06-17 15:58  蜗牛的礼物  阅读(84)  评论(0编辑  收藏  举报