Skip to content

Instantly share code, notes, and snippets.

@msehnout
Created August 2, 2016 15:32
Show Gist options
  • Save msehnout/306c6899905a76ad03bb0f5b04bed5fc to your computer and use it in GitHub Desktop.
Save msehnout/306c6899905a76ad03bb0f5b04bed5fc to your computer and use it in GitHub Desktop.
use std::env;
use std::io::{self, stdin, Read, Write, Result};
use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
use std::str;
use std::sync::Arc;
use std::thread;
static MAN_PAGE: &'static str = /* @MANSTART{tail} */ r#"
NAME
nc - Concatenate and redirect sockets
SYNOPSIS
nc [[-h | --help] | [[-u | --udp]] [hostname:port]
DESCRIPTION
TODO
OPTIONS
-h
--help
Print this manual page.
-u
--udp
Use UDP instead of default TCP
AUTHOR
Written by Sehny.
"#; /* @MANEND */
enum Options {
Tcp,
Udp,
}
fn connect_tcp(host: String) -> Result<()> {
let mut stream = TcpStream::connect(host.as_str()).unwrap();
let mut stream2 = stream.try_clone().unwrap();
thread::spawn(move || {
loop {
let mut buf = [0u8; 65536];
let count = stream2.read(&mut buf).unwrap();
print!("{}", unsafe { str::from_utf8_unchecked(&buf[..count]) });
}
});
loop {
let mut buffer = [0; 65536];
let count = stdin().read(&mut buffer).unwrap();
let _ = stream.write(&buffer[..count]).unwrap();
}
Ok(())
}
fn main() {
let mut args = env::args().skip(1);
let mut hostname = "".to_string();
let mut opt = Options::Tcp;
let mut stderr = io::stderr();
let mut stdout = io::stdout();
while let Some(arg) = args.next() {
if arg.starts_with('-') {
match arg.as_str() {
"-h" | "--help" => {
stdout.write_all(MAN_PAGE.as_bytes()).unwrap();
return;
}
"-u" | "--udp" => opt = Options::Udp,
_ => {
println!("Invalid argument!");
return;
}
}
} else {
hostname = arg;
break;
}
}
println!("Remote host: {}", hostname);
match opt {
Options::Tcp => connect_tcp(hostname).unwrap(),
Options::Udp => println!("Not implemented. udp"),
}
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment