Use of cidr crate

I am porting some existing code to Rust. I see that the cidr crate (at https://docs.rs/cidr/0.1.1/cidr/trait.Cidr.html) can help me. However, for the life of me, I am having difficulty in creating an object of type cidr. I think the part I am missing is how to tell it that the address is of type Ipv4. Any example or other help will be much appreciated.

Looking at that API, note that there's three types that implement the Cidr trait. One for IPv4 only, one for v6 only and one supporting both (being an enum of the other two). The respective cidr can be created from an address type (there's three of those too, following the same logic).

So for example to create a v6-only one you can call something like

Ipv6Cidr::new(Ipv6Addr::new(1,2,3,4,5,6,7,8), 42).unwrap()

with appropriate numerical values substituted in (my placeholder numbers will probably create an error).


Note that there's also a bunch of From<...> implementations for e. g. getting Ipv6Addr from an array or integer, and there's FromStr implementations for both the address and cidr types, so you could parse them from a string literal (probably using standard notation for up addresses and cidrs, but you'd need to test that, hypothesis).

1 Like

Thank you for the response. I will be constructing an Ipv4Address from a string and u8. The string will specify the address and the u8 will specify the length. I am still having issues, trying to use the syntax you provided.

I have:
cidr::Ipv4Cidr::new(cidr::Cidr::Ipv4Addr::new(1.2.3.4),16).unwrap();
gives me a warning of:
"
the value of the associated types Address (from trait cidr::Cidr), Inet (from trait cidr::Cidr) must be specified

help: specify the associated types: cidr::Cidr::Ipv4Addr::new<Address = Type, Inet = Type>rustc(E0191)

ambiguous associated type"
that I cannot find a way out of.

I wouldn't think that the IPv4 address type lives under cidr::Cidr

Edit: It's std::net::Ipv4Addr

To convert from string, you could try using std::net::Ipv4Addr::from_str("192.168.0.0").unwrap(). Haven't tested it (I'm on my phone right now), but it might work.

Edit: Or actually just "192.168.0.0".parse().unwrap() should work when you pass it to the cidr constructor so the compiler knows the type.

Thank you so much! The following worked:

cidr::Ipv4Cidr::new(std::net::Ipv4Addr::new(1,2,3,4),16).unwrap();

Thank you again for your prompt responses.

Got to using something like cidr::Ipv4Cidr::new("1,2,3,4".parse().unwrap(),16).unwrap(); which is working fine. The call to parse() throws a warning about it being better to have it separate due to possibility of panic. Looking into that now.