Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

tcp

TCP的握手有三个过程,首先客户端发送一个syn的包,表示建立回话的开始,如果客户端收到超时,说明端口可能在防火墙后面。如果服务器应答了syn-ack包,意味着端口被打开了,否则会返回rst包,最后客户端需要另外发送一个ack包,此时连接已经建立。

项目说明

使用标准库中的net.Dial函数实现单个端口的测试

接下来利用flag包配置每个字符串或数字,以此方便修改数据

利用for循环逐一扫描

  • 此时程序运行得极慢

建立协程,加锁

源码

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)
}

本文转自:https://mp.weixin.qq.com/s/OhS_RQZojJbkenOSS_tEng

评论