Reputation: 2624
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.
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
}
From this package: https://github.com/janosgyerik/portping
portping -c 3 -net udp 0.0.0.0.0 80
Upvotes: 1
Views: 4951
Reputation: 21
Since UDP doesn't provide anything like "connection", it seems to me that the only way to check if remote UDP server is running - is to send a meaningful message, which is understandable by the server and requires "response" to that. Then we just have to wait for server reply and if there is one - the server is OK.
Again, for UDP we have to make several sendings, because if server is down, it won't receive the packet.
Following all that logic i've implemented GO library/cli utility supporting both UDP and TCP library and working the way described above.
Upvotes: 2
Reputation: 828
You can't unless you know for sure that the server will send something back, then you can try to catch the response.
Check this link https://ops.tips/blog/udp-client-and-server-in-go/
Upvotes: 3