我正在尝试在Rust中实现VXI11协议(与示波器、电源等仪器通信),我成功地发送了一条广播的UDP消息,但没有接收到响应。这是我用来设置UDP套接字的代码:
let socket:UdpSocket = UdpSocket::bind("0.0.0.0:0")?;
socket.set_read_timeout(Some(Duration::new(5, 0)))?;
socket.set_broadcast(true)?;
socket.connect(("255.255.255.255", port))?;
println!("Connected on port {}", port);
println!("Broadcast: {:?}", socket.broadcast());
println!("Timeout: {:?}", socket.read_timeout());我还在bind调用中尝试了"255.255.255.255:0“和"192.168.2.255:0”,没有结果。这是我用来接收响应的代码。
let call:Vec<u8> = self.packer.get_buf()?;
println!("Sending call, {} bytes", call.len());
match self.socket.send(&call) {
Ok(n) => {
if n != call.len() {
return Err(Error::new(ErrorKind::Other, "Sent the wrong number of bytes"))
}
else {
// Do nothing because we sent the number of bytes we expected to send
}
},
Err(e) => return Err(e),
}
println!("Awaiting responses..."); // self.recv_buff is a [u8; 8092]
while let Ok((n, addr)) = self.socket.recv_from(&mut self.recv_buff) {
println!("{} bytes response from {:?}", n, addr);
// Remaining code not directly relevant to the question
}这是STDOUT输出:
Connected on port 111
Broadcast: Ok(true)
Timeout: Ok(Some(5s))
Sending call, 56 bytes
Awaiting responses...我还知道远程主机正在响应,因为我可以在tcpdump中看到它。然而,锈蚀代码只是没有收到响应。有人知道为什么会这样吗?
$ sudo tcpdump 'udp port 111'
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on wlo1, link-type EN10MB (Ethernet), capture size 262144 bytes
11:00:54.094534 IP deathStar.51499 > 255.255.255.255.sunrpc: UDP, length 56
11:00:54.100199 IP 192.168.2.4.sunrpc > deathStar.51499: UDP, length 28
11:00:54.100755 IP 192.168.2.3.sunrpc > deathStar.51499: UDP, length 28发布于 2020-04-07 03:23:08
TL;博士删除UdpSocket::connect调用,然后重试。那就行了。
看起来UdpSocket::connect是根本原因。基于文档,如果套接字必须处理来自具体远程地址的数据,则应该使用UdpSocket::connect。如果不知道远程地址,那么就可以完全避免connect调用。如果没有connect调用,套接字将从任何远程地址接收数据。
let socket:UdpSocket = UdpSocket::bind("0.0.0.0:0")?;
socket.set_read_timeout(Some(Duration::new(5, 0)))?;
socket.set_broadcast(true)?;
println!("Connected on port {}", port);
println!("Broadcast: {:?}", socket.broadcast());
println!("Timeout: {:?}", socket.read_timeout());
let call:Vec<u8> = self.packer.get_buf()?;
println!("Sending call, {} bytes", call.len());
match self.socket.send(&call) {
Ok(n) => {
if n != call.len() {
return Err(Error::new(ErrorKind::Other, "Sent the wrong number of bytes"))
}
else {
// Do nothing because we sent the number of bytes we expected to send
}
},
Err(e) => return Err(e),
}
println!("Awaiting responses..."); // self.recv_buff is a [u8; 8092]
while let Ok((n, addr)) = self.socket.recv_from(&mut self.recv_buff) {
println!("{} bytes response from {:?}", n, addr);
// Remaining code not directly relevant to the question
}https://stackoverflow.com/questions/61045602
复制相似问题