Created
April 27, 2022 02:40
-
-
Save ssrlive/6b5d95c7a1847b2ef9c0efc6d452c16e to your computer and use it in GitHub Desktop.
TCP connectivity test in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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