Home > OS >  Converting bytes from UDP Server
Converting bytes from UDP Server

Time:04-28

I am creating a windows UDP tunnel using wintun driver. I have written a code to receive data from the server and send it to the windows tunnel using the function send_packet and allocatesendpacket. The error I get is that I can read data only as bytes from the UDP server but it causes a mismatch when I pass it to the send_packet function. The error is as follows:

mismatched types
expected struct `wintun::Packet`, found `&[u8]`

Code for send_packet and allocatesendpacket https://github.com/nulldotblack/wintun/blob/main/src/session.rs

Code for packet struct data type https://github.com/nulldotblack/wintun/blob/main/src/packet.rs

Link for other dependencies https://github.com/nulldotblack/wintun

How do I convert the bytes (variable buffer below) to Packet struct data type?. The error of mismatch occurs when I declare the value of a variable packet with the value of the received buffer variable, so that packet variable can be sent to tunnel.

My code:

    let socket = UdpSocket::bind("6.0.0.1:8000") //create client socket object with ip and port
                       .expect("Could not bind client socket");

    socket.connect("6.0.0.10:8888") //SERVER IP /PORT

let writer_session = session.clone();
let writer =
 std::thread::spawn(move || {
    info!("Starting writer");

    while RUNNING.load(Ordering::Relaxed) {
        let mut buffer = [0u8; 20000]; 
                socket.recv_from(&mut buffer) //get message from server
                     .expect("Could not read into buffer");
        let leng1 = buffer.len();



                let mut packet = writer_session.allocate_send_packet(leng1.try_into().unwrap()).unwrap();
                packet = &buffer[0..leng1];  //ERROR occurs here
                writer_session.send_packet(packet);
                    
    }
});

CodePudding user response:

To copy the contents of buffer into packet, you can use slice::copy_from_slice:

packet.bytes_mut().copy_from_slice(&buffer);

CodePudding user response:

You have two errors the first caused by trying to assign a slice to packet directly which is solved by copying the buffer into packet instead:

packet.bytes_mut().copy_from_slice(&buffer);

The second is that you are not using the length returned by recv_from but instead using the length of the whole buffer which may lead to reading past the end of the read data although memory address is valid. You should do this instead:

let mut buffer = [0u8; 20000]; 
let (leng1, src_addr) = socket.recv_from(&mut buffer) //get message from server
                     .expect("Could not read into buffer");
let buffer = &mut buffer[..leng1];
  • Related