Skip to content

Commit

Permalink
Merge pull request #3 from leshow/macos_sendpktinfo
Browse files Browse the repository at this point in the history
fix(macos): use pktinfo for src ip send
  • Loading branch information
leshow authored May 1, 2023
2 parents fed7cc8 + 462d52a commit 60b63cb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
));
}
}
4 changes: 2 additions & 2 deletions src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -996,7 +996,7 @@ fn prepare_msg<B: AsPtr<u8>>(
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,
Expand All @@ -1007,7 +1007,7 @@ fn prepare_msg<B: AsPtr<u8>>(
};
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()),
Expand Down

0 comments on commit 60b63cb

Please sign in to comment.