Created
July 16, 2019 17:23
-
-
Save piersy/136d18ebeb1a64bea363e589f6e4babd to your computer and use it in GitHub Desktop.
Check if a tcp connection can connect back to the same host via it's public IP (hint, it can!)
This file contains 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 ( | |
"context" | |
"fmt" | |
"net" | |
"time" | |
) | |
func main() { | |
l, err := net.Listen("tcp", ":9091") | |
if err != nil { | |
panic(err) | |
} | |
go func() { | |
c, err := l.Accept() | |
if err != nil { | |
panic(err) | |
} | |
msg := make([]byte, 5) | |
n, err := c.Read(msg) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("read %d bytes from connection %q\n", n, string(msg)) | |
}() | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
defer cancel() | |
var d net.Dialer | |
c, err := d.DialContext(ctx, "tcp", "your_public_ip") | |
if err != nil { | |
panic(err) | |
} | |
n, err := c.Write([]byte("hello")) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("wrote %d bytes of hello to connection\n", n) | |
time.Sleep(time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment