Skip to content

Instantly share code, notes, and snippets.

@akutz
Last active March 3, 2019 18:31
Show Gist options
  • Save akutz/9501a17d7977ba1eb74d8ec5c80c7a3d to your computer and use it in GitHub Desktop.
Save akutz/9501a17d7977ba1eb74d8ec5c80c7a3d to your computer and use it in GitHub Desktop.
Testing TCP Endpoints with Go

This gist demonstrates how to test the availability of a TCP endponit using Golang. The following example checks if an endpoint is available and responding to both TCP and TLS connections. To run the example, simply open a command line and execute the following:

$ curl -sSL https://goo.gl/ENx9d8 > tcp-tls-ping.go && go run tcp-tls-ping.go
tcp success
tls success

The program shows that the specified endpoint (defaults to google.com:443) is available and responding to TCP and TLS connection attempts. To illustrate the error that occurs when an endpoint presents an invalid TLS certificate, execute the following:

$ curl -sSL https://goo.gl/ENx9d8 > tcp-tls-ping.go && go run tcp-tls-ping.go www.pcwebshop.co.uk:443
tcp success
tls error: x509: certificate is valid for *.secure-secure.co.uk, secure-secure.co.uk, not www.pcwebshop.co.uk
exit status 1

Finally, the program can also demonstrate that a TCP endpoint is unavailable:

$ curl -sSL https://goo.gl/ENx9d8 > tcp-tls-ping.go && go run tcp-tls-ping.go google.com:444
tcp error: dial tcp [2607:f8b0:4000:80a::200e]:444: i/o timeout
exit status 1
package main
import (
"crypto/tls"
"fmt"
"net"
"os"
"time"
)
func main() {
var (
proto = "tcp"
endpoint = "google.com:443"
dialer = &net.Dialer{Timeout: time.Second * 1}
)
switch len(os.Args) {
case 2:
endpoint = os.Args[1]
case 3:
proto = os.Args[1]
endpoint = os.Args[2]
}
if _, err := dialer.Dial(proto, endpoint); err != nil {
fmt.Printf("tcp error: %v\n", err)
os.Exit(1)
}
fmt.Println("tcp success")
if _, err := tls.DialWithDialer(
dialer, proto, endpoint, &tls.Config{}); err != nil {
fmt.Printf("tls error: %v\n", err)
os.Exit(1)
}
fmt.Println("tls success")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment