【发布时间】:2020-06-27 09:40:08
【问题描述】:
如何检查特定的 UDP 端口是否在 golang 中打开?
到目前为止,我已经尝试了很多方法,但没有一个奏效。 准确地说,所有这些,只要告诉服务器是否响应,无论我输入什么端口。
方法一
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 是无连接的,这些方法都不起作用。如果端口是开放的,则由应用层来回答(或不回答)。如果它已关闭,您可能会返回 ICMP 错误。使用 UDP ping 可以做的最好的事情是进行大量假设并将某些事情视为成功。
标签: go networking udp