Rfcs: Provide std::net::IpAddr#octets

Created on 2 Feb 2017  路  6Comments  路  Source: rust-lang/rfcs

Both Ipv4Addr and Ipv6Addr provide the octets() method. The union type should provide it too.

fn octets(&self) -> std::vec<u8>

The downside of this API is that it "requires" an allocation since the size is not known. Alternative interfaces would be to return/take a buffer large enough for either v4 or v6.

T-libs

Most helpful comment

Sorry, it's a bit late; you're right.

I think that this method isn't great for inclusion in libstd, but feel free to implement it in your own crate. Here's an example I thought of that doesn't require allocation: https://is.gd/C4QOXX

All 6 comments

Why would you want to know the octets without already knowing whether you're dealing with an IPv6 or IPv4 address?

After pondering this a bit more I realize it is largely a niche use case. I was hashing the IP and I wanted to support both. I think I will open another issue with a request for something like to_ipv6_mapped() for both (ipv6 returning itself) as that would me more generally useful.

I don't actually think this is a bad idea. It wouldn't require an allocation because you're returning slices.

@clarcharr It would because they're not stored as octet arrays. Alternatively, this method could return some form of ArrayVec with a capacity of 8 but the standard library doesn't have ArrayVecs.

Sorry, it's a bit late; you're right.

I think that this method isn't great for inclusion in libstd, but feel free to implement it in your own crate. Here's an example I thought of that doesn't require allocation: https://is.gd/C4QOXX

I came across this problem today while trying to figure out how to relay one node's IP address to another node in a distributed network. When you receive a SocketAddr from recv_from() your only option as far as I can see is an ugly solution like this:

let bytes = match sockaddr.ip() {
    IpAddr::V4(ip) => ip.octets().to_vec(),
    IpAddr::V6(ip) => ip.octets().to_vec(),
};

I'm still learning Rust, but it seems like a pretty intuitive thing to just be able to do something like:

let bytes = sockaddr.ip().octets()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

steveklabnik picture steveklabnik  路  4Comments

clarfonthey picture clarfonthey  路  3Comments

yongqli picture yongqli  路  3Comments

camden-smallwood-zz picture camden-smallwood-zz  路  3Comments

mqudsi picture mqudsi  路  3Comments