I have a service where multiple other separated devices can connect to. I would like to simulate these other devices on the same machine as the service. For this, I would like to have a simulation that listens to the messages sent by the service and that responds with the IP address that corresponds to the devices that is the receiver of the message.
I currently have this program.
use anyhow::Result;
use std::net::{Ipv4Addr, SocketAddrV4};
use tokio::net::UdpSocket;
#[tokio::main]
async fn main() -> Result<()> {
let local_addr = SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 14551);
let socket = UdpSocket::bind(local_addr).await?;
let mut buf = [0; 1024];
loop {
let (len, addr) = socket.recv_from(&mut buf).await?;
println!(
"Received packet from {} to {}: {:?}",
addr.ip(),
socket.local_addr()?.ip(),
&buf[..len],
);
}
}
When I run this program I get the following:
Received packet from 192.168.1.27 to 0.0.0.0: [253, 9, 0, 0, 156, 0, 255, 0, 0, 0, 0, 0, 0, 0, 6, 8, 0, 0, 3, 173, 1]
How can I obtain the client address connected to this server, rather than 0.0.0.0
?
Is this possible to do this with tokio
or do I have to manually parse received frames and inject the response frames?