从UDP服务器转换字节
我正在使用Wintun驱动程序创建Windows UDP隧道。我已经编写了一个代码,以从服务器接收数据,并使用函数send_packet和分配Packet将其发送到Windows隧道。我收到的错误是,我只能从UDP服务器中读取数据,但是当我将其传递给send_packet函数时会导致不匹配。错误如下:
mismatched types
expected struct `wintun::Packet`, found `&[u8]`
其他依赖关系的链接 https://github.com/nulldotblack/wintun
如何转换tock(下面的可变缓冲区)到数据包结构数据类型?当我声明带有接收缓冲区变量的值的变量数据包的值时,不匹配的错误就会发生,因此可以将数据包变量发送到隧道。
我的代码:
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);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到了两个错误,第一个错误是通过尝试将切片分配给数据包的第一个错误,这是通过将缓冲区复制到数据包中来解决的:
第二个是您不使用
recv_from
的长度,而是使用。尽管内存地址有效,但可能会导致读取数据末尾的整个缓冲区的长度。您应该这样做: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:
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:要将
Buffer
的内容复制到packet
中,您可以使用slice :: copy_from_slice
:To copy the contents of
buffer
intopacket
, you can useslice::copy_from_slice
: