How can I check if a specific UDP port is open in golang?
Until now I have tried many methods, but no one worked. Precisely, all of them, just tell if the server is responding, no matter what port I input.
METHOD ONE
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
}
METHOD TWO
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
}
METHOD THREE
From this package: https://github.com/janosgyerik/portping
portping -c 3 -net udp 0.0.0.0.0 80