From 462d52a75939fec8e52e173cc8d1aa8ab5350406 Mon Sep 17 00:00:00 2001 From: Evan Cameron Date: Mon, 1 May 2023 13:21:47 -0400 Subject: [PATCH] fix(macos): use pktinfo for src ip send --- src/lib.rs | 25 +++++++++++++++++++++++++ src/unix.rs | 4 ++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e241499..29e034e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -162,4 +162,29 @@ mod tests { Some(addr) if addr == send_addr || addr == IpAddr::V4(Ipv4Addr::LOCALHOST) )); } + #[test] + fn test_send_recv_msg_ip() { + let saddr = "0.0.0.0:9903".parse().unwrap(); + let a = sync::UdpSocket::bind(saddr).unwrap(); + let b = sync::UdpSocket::bind("0.0.0.0:0").unwrap(); + let send_port = b.local_addr().unwrap().port(); + let send_addr = b.local_addr().unwrap().ip(); + let buf = b"hello world"; + let src = Source::Ip("0.0.0.0".parse().unwrap()); + let tr = Transmit::new(saddr, *buf).src_ip(src); + b.send_msg(&UdpState::new(), tr).unwrap(); + // recv + let mut r = [0; 1024]; + let meta = a.recv_msg(&mut r).unwrap(); + assert_eq!(buf[..], r[..11]); + // dst addr and b addr matches! + // meta.ifindex + assert_eq!(send_port, meta.addr.port()); + assert_eq!(meta.ifindex, 1); + assert!(matches!( + meta.dst_local_ip, + // dst_local_ip might be 127.0.0.1 + Some(addr) if addr == send_addr || addr == IpAddr::V4(Ipv4Addr::LOCALHOST) + )); + } } diff --git a/src/unix.rs b/src/unix.rs index 0cf3354..4a0e0b7 100644 --- a/src/unix.rs +++ b/src/unix.rs @@ -996,7 +996,7 @@ fn prepare_msg>( if let Some(ip) = &transmit.src { match ip { Source::Ip(IpAddr::V4(v4)) => { - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "macos"))] { let pktinfo = libc::in_pktinfo { ipi_ifindex: 0, @@ -1007,7 +1007,7 @@ fn prepare_msg>( }; encoder.push(libc::IPPROTO_IP, libc::IP_PKTINFO, pktinfo); } - #[cfg(any(target_os = "freebsd", target_os = "macos"))] + #[cfg(target_os = "freebsd")] { let addr = libc::in_addr { s_addr: u32::from_ne_bytes(v4.octets()),