-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
63 lines (54 loc) · 1.23 KB
/
tcp.go
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
54
55
56
57
58
59
60
61
62
63
package libtower
import (
"context"
"crypto/tls"
"net"
"net/url"
"time"
)
// TCP type
type TCP struct {
URL *url.URL
Timeout time.Duration
CertFile string
PrivateKeyFile string
Start time.Time
End time.Time
Duration time.Duration
}
// TCPPortCheck checks if a tcp port is open
func (tr *TCP) TCPPortCheck(ctx context.Context) (bool, error) {
tr.Start = time.Now()
conn, err := net.DialTimeout("tcp", tr.URL.Host, tr.Timeout)
tr.End = time.Now()
tr.Duration = tr.End.Sub(tr.Start)
if err != nil {
return false, err
}
if conn != nil {
defer conn.Close()
return true, nil
}
return false, nil
}
// TLSPortCheck check if a scured tcp port is open
func (tr *TCP) TLSPortCheck(ctx context.Context) (bool, error) {
cert, err := tls.LoadX509KeyPair(tr.CertFile, tr.PrivateKeyFile)
if err != nil {
return false, err
}
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
tr.Start = time.Now()
conn, err := net.DialTimeout("tcp", tr.URL.Host, tr.Timeout)
if err != nil {
return false, err
}
tlsConn := tls.Client(conn, &config)
err = tlsConn.Handshake()
if err != nil {
return false, err
}
tr.End = time.Now()
tr.Duration = tr.End.Sub(tr.Start)
return true, nil
}