Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Created April 27, 2022 02:40
Show Gist options
  • Save ssrlive/6b5d95c7a1847b2ef9c0efc6d452c16e to your computer and use it in GitHub Desktop.
Save ssrlive/6b5d95c7a1847b2ef9c0efc6d452c16e to your computer and use it in GitHub Desktop.
TCP connectivity test in golang
package main
import (
"fmt"
"net"
"time"
)
func main() {
host := "baidu.com"
port := "443"
if result, err := raw_connect(host, port); result {
fmt.Println("Opened", net.JoinHostPort(host, port))
} else {
fmt.Println("Connecting error:", err)
}
}
func raw_connect(host string, port string) (bool, error) {
result := false
timeout := time.Second
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err == nil {
result = true
}
if conn != nil {
defer conn.Close()
}
return result, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment