Joh*_*ord 4 ip networking udp rust
我正在尝试在 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());
Run Code Online (Sandbox Code Playgroud)
我还在绑定调用中尝试过“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
}
Run Code Online (Sandbox Code Playgroud)
这是 STDOUT 输出:
Connected on port 111
Broadcast: Ok(true)
Timeout: Ok(Some(5s))
Sending call, 56 bytes
Awaiting responses...
Run Code Online (Sandbox Code Playgroud)
我还知道远程主机正在响应,因为我可以在 tcpdump 中看到它。然而,Rust 代码只是没有收到响应。任何人都知道为什么会这样?
$ 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
Run Code Online (Sandbox Code Playgroud)
TL;DR删除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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7966 次 |
| 最近记录: |