Search code examples
rustipip-address

How to convert an IP to a u32 and back?


I am wondering how to convert an IPv4 address from and to u32:

use std::net::Ipv4Addr;
let addr = Ipv4Addr::new(127, 0, 0, 1);
...

Solution

  • There are conversion implementations available, From<Ipv4Addr> for u32 and From<u32> for Ipv4Addr, so you can use .into() or T::from() to swap between them.

    let addr = Ipv4Addr::new(127, 0, 0, 1);
    let addr_u32: u32 = addr.into();
    let addr = Ipv4Addr::from(addr_u32);