Skip to content

Commit

Permalink
mod: tcp-ping 加入对RST回包的判断,并且在有一个端口有回应时停止对其它端口的请求
Browse files Browse the repository at this point in the history
  • Loading branch information
XinRoom committed Mar 22, 2023
1 parent 1124d59 commit 11829e4
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion core/host/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package host

import (
"bytes"
"context"
"fmt"
"github.com/go-ping/ping"
"net"
Expand Down Expand Up @@ -88,14 +89,24 @@ func IcmpOK(host string) bool {
// TcpPing 指定默认常见端口进行存活探测
func TcpPing(host string, ports []uint16, timeout time.Duration) (ok bool) {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
d := net.Dialer{
Timeout: timeout + time.Second,
KeepAlive: 0,
}
for _, port := range ports {
time.Sleep(10 * time.Millisecond)
wg.Add(1)
go func(_port uint16) {
conn, _ := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", host, _port), timeout)
conn, err := d.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", host, _port))
if conn != nil {
conn.Close()
ok = true
} else if err != nil && strings.Contains(err.Error(), "refused it") { // 表明对端发送了RST包
ok = true
}
if ok {
cancel()
}
wg.Done()
}(port)
Expand Down

0 comments on commit 11829e4

Please sign in to comment.