我需要检查远程地址是否打开了特定的 TCP 端口。为此,我选择使用 golang。到目前为止,这是我的尝试:
func raw_connect(host string, ports []string) {
for _, port := range ports {
timeout := time.Second
conn, err := net.DialTimeout("tcp", host + ":" + port, timeout)
if err != nil {
_, err_msg := err.Error()[0], err.Error()[5:]
fmt.Println(err_msg)
} else {
msg, _, err := bufio.NewReader(conn).ReadLine()
if err != nil {
if err == io.EOF {
fmt.Print(host + " " + port + " - Open!\n")
}
} else {
fmt.Print(host + " " + port + " - " + string(msg))
}
conn.Close()
}
}
}
Run Code Online (Sandbox Code Playgroud)
当应用程序(例如 SSH)首先返回一个字符串时,这对于 TCP 端口来说工作得很好,我立即读取并打印它。
但是,当 TCP 之上的应用程序首先等待来自客户端的命令(如 HTTP)时,就会出现超时(if err == io.EOF子句)。
这个超时时间很长。我需要立即知道端口是否打开。
是否有更适合此目的的技术?
非常感谢!
小智 11
要检查端口,您可以检查连接是否成功。例如:
func raw_connect(host string, ports []string) {
for _, port := range ports {
timeout := time.Second
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
fmt.Println("Connecting error:", err)
}
if conn != nil {
defer conn.Close()
fmt.Println("Opened", net.JoinHostPort(host, port))
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11671 次 |
| 最近记录: |