检查Golang中TCP端口状态
时间:2024-03-20
浏览:280
作者:佚名
在 Go 语言中,检查 TCP 端口状态是一个常见需求。本文介绍了两种方法: * **直接连接方法**:通过 `net.DialTimeout` 直接连接到远程地址,如果连接成功,则表示端口已打开。 * **多端口检查方法**:使用 `net.DialTimeout` 同时检查多个端口,并返回一个包含每个端口状态的映射。
问题内容
我需要检查远程地址是否打开了特定的 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()
}
}
}
当应用程序(例如 ssh)首先返回一个字符串时,这对于 tcp 端口工作得很好,我立即读取并打印它。
但是,当tcp之上的应用程序首先等待客户端的命令时(例如http),就会出现超时(if err == io.eof子句)。
这个超时时间相当长。我需要立即知道端口是否打开。
是否有更适合此目的的技术?
非常感谢!
解决方案
检查端口,可以检查连接是否成功。例如:
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))
}
}
}检查多个端口示例
func tcpGather(ip string, ports []string) map[string]string {
// check emqx 1883, 8083 port
results := make(map[string]string)
for _, port := range ports {
address := net.JoinHostPort(ip, port)
// 3 second timeout
conn, err := net.DialTimeout("tcp", address, 3*time.Second)
if err != nil {
results[port] = "failed"
// todo log handler
} else {
if conn != nil {
results[port] = "success"
_ = conn.Close()
} else {
results[port] = "failed"
}
}
}
return results
}本篇关于《检查Golang中TCP端口状态》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.02
12.02
12.02
12.02
12.02
12.02
热门专题
