winping-rs 0.11.0

An easy-to-use ICMP Echo API for Windows programs without requiring elevated rights.
Documentation
use core::net::{Ipv4Addr, Ipv6Addr};

use windows_sys::Win32::Networking::WinSock::{IN6_ADDR, IN6_ADDR_0};

/// Converts a Rust IPv4 to a Windows IPv4
pub(crate) fn windows_ipv4(ip: Ipv4Addr) -> u32 {
    u32::from_ne_bytes(ip.octets())
}

/// Converts a Windows IPv4 to a Rust IPv4
pub(crate) fn rust_ipv4(ip: u32) -> Ipv4Addr {
    Ipv4Addr::from(ip.to_ne_bytes())
}

/// Converts a Rust IPv6 to a Windows IPv6
pub(crate) fn windows_ipv6(ip: Ipv6Addr) -> IN6_ADDR {
    IN6_ADDR {
        u: IN6_ADDR_0 { Byte: ip.octets() },
    }
}

/// Converts a Windows IPv6 to a Rust IPv6
#[expect(clippy::many_single_char_names, reason = "a..h mirror the eight IPv6 segments")]
pub(crate) fn rust_ipv6(ip: [u16; 8]) -> Ipv6Addr {
    let [a, b, c, d, e, f, g, h] = ip;
    Ipv6Addr::new(
        u16::from_be(a),
        u16::from_be(b),
        u16::from_be(c),
        u16::from_be(d),
        u16::from_be(e),
        u16::from_be(f),
        u16::from_be(g),
        u16::from_be(h),
    )
}

#[test]
fn ip_conv_is_correct() {
    let localhost_u32be = 0x7f00_0001u32.to_be();
    assert_eq!(localhost_u32be, windows_ipv4(Ipv4Addr::LOCALHOST));
    assert_eq!(Ipv4Addr::LOCALHOST, rust_ipv4(localhost_u32be));

    let localhost6_segments_be = [0, 0, 0, 0, 0, 0, 0, 1u16.to_be()];
    // SAFETY: IN6_ADDR_0 is a union of two arrays of the same size, and both
    // [u8; 16] and [u16; 8] are valid for any bit pattern.
    assert_eq!(localhost6_segments_be, unsafe {
        windows_ipv6(Ipv6Addr::LOCALHOST).u.Word
    });
    assert_eq!(Ipv6Addr::LOCALHOST, rust_ipv6(localhost6_segments_be));
}