Created
May 29, 2021 13:38
-
-
Save jcgregorio/f40f60f78243a3c903d37effdcb7941f to your computer and use it in GitHub Desktop.
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
// ncrev is essentially "nc -l NNNN", i.e. netcat listening on a port and | |
// directing the traffic to stdin/stdout, but it first checks that nothing is | |
// already listening on port NNNN. | |
package main | |
import ( | |
"flag" | |
"io" | |
"log" | |
"net" | |
"os" | |
"sync" | |
) | |
var port = flag.String("port", "", `The port to listen on, e.g. ":4000"`) | |
func main() { | |
flag.Parse() | |
if *port == "" { | |
log.Fatal("Port is required.") | |
} | |
// First start a connection to the local port. If there is already a | |
// listener there then we should fail out. | |
conn, err := net.Dial("tcp", *port) | |
if err == nil { | |
conn.Close() | |
log.Fatalf("Found a listener at port %q", *port) | |
} | |
// Now listen for a connection. | |
ln, err := net.Listen("tcp", *port) | |
if err != nil { | |
log.Fatalf("Failed to listen on port %q: %s", *port, err) | |
} | |
conn, err = ln.Accept() | |
if err != nil { | |
log.Fatalf("Failed to accept connection on port %q: %s", *port, err) | |
} | |
defer conn.Close() | |
var wg sync.WaitGroup | |
wg.Add(1) // We will exit once one of the streams is closed. | |
go func() { | |
defer wg.Done() | |
if _, err := io.Copy(conn, os.Stdin); err != nil { | |
log.Fatalf("Failed while streaming stdin to port %q: %s", *port, err) | |
} | |
}() | |
go func() { | |
defer wg.Done() | |
if _, err := io.Copy(os.Stdout, conn); err != nil { | |
log.Fatalf("Failed while streaming stdout from port %q: %s", *port, err) | |
} | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment