0

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?

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • It [seems possible in C](https://stackoverflow.com/questions/5281409/get-destination-address-of-a-received-udp-packet) though I don't know how to translate that to Rust (yet). A workaround from the link, create a different `UdpSocket` per interface, that way the socket you receive data on uniquely identifies it. – cafce25 Mar 27 '23 at 14:44
  • also, maybe look at what pcap can do. – Stargateur Mar 27 '23 at 15:31
  • I ended up using the crate [udp_sas](https://github.com/a-ba/udp_sas) which uses `IP_PKTINFO` under the hood. – Jonathan Mar 30 '23 at 16:55

0 Answers0