golang 检查 udp 端口打开
golang check udp port open
如何检查 golang 中是否打开了特定的 UDP 端口?
到目前为止,我已经尝试了很多方法,但没有一个奏效。
准确地说,所有这些,只要告诉服务器是否响应,无论我输入什么端口。
方法一
func methodOne(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("udp", 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
}
方法二
func ping(host string, port string) error {
address := net.JoinHostPort(host, port)
conn, err := net.DialTimeout("udp", address, 1*time.Second)
if conn != nil {
fmt.Println(conn.LocalAddr())
defer conn.Close()
}
return err
}
方法三
来自这个包:https://github.com/janosgyerik/portping
portping -c 3 -net udp 0.0.0.0.0 80
你不能,除非你确定服务器会发回一些东西,然后你可以尝试捕捉响应。
由于 UDP 不提供任何类似“连接”的功能,
在我看来,检查远程 UDP 服务器是否为 运行 的唯一方法是发送有意义的消息,服务器可以理解该消息并需要对此进行“响应”。然后我们只需要等待服务器回复,如果有 - 服务器就可以了。
同样,对于 UDP,我们必须进行多次发送,因为如果服务器宕机,它将收不到数据包。
按照所有这些逻辑,我已经实现了支持 UDP 和 TCP 库并按照上述方式工作的 GO library/cli 实用程序。
如何检查 golang 中是否打开了特定的 UDP 端口?
到目前为止,我已经尝试了很多方法,但没有一个奏效。 准确地说,所有这些,只要告诉服务器是否响应,无论我输入什么端口。
方法一
func methodOne(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("udp", 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
}
方法二
func ping(host string, port string) error {
address := net.JoinHostPort(host, port)
conn, err := net.DialTimeout("udp", address, 1*time.Second)
if conn != nil {
fmt.Println(conn.LocalAddr())
defer conn.Close()
}
return err
}
方法三
来自这个包:https://github.com/janosgyerik/portping
portping -c 3 -net udp 0.0.0.0.0 80
你不能,除非你确定服务器会发回一些东西,然后你可以尝试捕捉响应。
由于 UDP 不提供任何类似“连接”的功能, 在我看来,检查远程 UDP 服务器是否为 运行 的唯一方法是发送有意义的消息,服务器可以理解该消息并需要对此进行“响应”。然后我们只需要等待服务器回复,如果有 - 服务器就可以了。
同样,对于 UDP,我们必须进行多次发送,因为如果服务器宕机,它将收不到数据包。
按照所有这些逻辑,我已经实现了支持 UDP 和 TCP 库并按照上述方式工作的 GO library/cli 实用程序。