in_addr/
lib.rs

1//! This crate exposes a common interface to in_addr between Unix and Windows.
2//!
3//! There are two types in this crate.
4//! * `in_addr`, a type alias to the platform specific version of this type. Use this in the
5//!   signature of `extern` functions.
6//! * `InAddr`, a newtype wrapper around `in_addr`. It implements conversions to and from `u32`,
7//!   `std::net::Ipv4Addr`, and `in_addr`.
8//!
9//! # Example
10//!
11//! ```
12//! extern {
13//!   fn inet_ntoa(addr: *const in_addr::in_addr) -> *const std::os::raw::c_char;
14//! }
15//!
16//! fn main() {
17//!   let addr = in_addr::InAddr::new(std::net::Ipv4Addr::LOCALHOST);
18//!   let addr_text = unsafe { std::ffi::CStr::from_ptr(inet_ntoa(&addr.into())) };
19//!   println!("The address is {}.", addr_text.to_string_lossy());
20//! }
21//! ```
22
23#![cfg_attr(not(feature = "std"), no_std)]
24
25#[cfg(unix)]
26mod unix;
27
28#[cfg(windows)]
29mod windows;
30
31#[cfg(unix)]
32pub use crate::unix::*;
33
34#[cfg(windows)]
35pub use crate::windows::*;
36
37impl InAddr {
38  pub fn new<T: Into<Self>>(t: T) -> Self {
39    t.into()
40  }
41}
42
43impl From<in_addr> for InAddr {
44  fn from(in_addr: in_addr) -> Self {
45    InAddr(in_addr)
46  }
47}
48
49impl From<InAddr> for in_addr {
50  fn from(InAddr(addr): InAddr) -> Self {
51    addr
52  }
53}
54
55#[cfg(feature = "std")]
56impl std::fmt::Debug for InAddr {
57  fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
58    Into::<std::net::Ipv4Addr>::into(*self).fmt(formatter)
59  }
60}
61
62#[cfg(feature = "std")]
63impl From<std::net::Ipv4Addr> for InAddr {
64  fn from(addr: std::net::Ipv4Addr) -> Self {
65    Into::<u32>::into(addr).into()
66  }
67}
68
69#[cfg(feature = "std")]
70impl From<InAddr> for std::net::Ipv4Addr {
71  fn from(addr: InAddr) -> Self {
72    Into::<u32>::into(addr).into()
73  }
74}