golang 端口扫描

端口扫描

简要端口扫描程序代码,可通过用户输入及端口扫描并获得状态。

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
package  main

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

//定义flag
var (
serverIp = flag.String("ip", "", "Server Ip address")
startPort = flag.Int("s", 0, "Start Port")
endPort = flag.Int("n", 0, "End Port")
)

// checkPort 检查端口状态
func checkPort(ip string,port int,wg *sync.WaitGroup){

defer wg.Done()
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), time.Second * 2)

if err == nil{
fmt.Printf("端口打开-------------:%v\n",port)
conn.Close() //关闭连接
}
}

func main(){

//解析flag输入
flag.Parse()


if flag.NFlag() <= 1 { //Flag返回解析时进行了设置的flag的数量。
flag.Usage() //当参数小于1个打印flag的默认提示
os.Exit(1)
}

var wg sync.WaitGroup

for i:=*startPort;i<*endPort;i++{
wg.Add(1)

go checkPort(*serverIp,i,&wg)
}

wg.Wait()
fmt.Printf("扫描完毕\n")

}

执行结果

编译

1
go build GoPortScan.go

使用方法

1
2
3
4
5
6
7
Usage of GoPortScan.exe:
-ip string
Server Ip address
-n int
End Port
-s int
Start Port

执行结果

1
2
3
4
GoPortScan.exe -ip 36.110.236.68 -s 1 -n 9090
端口打开-------------:80
端口打开-------------:443
扫描完毕