pub fn list_afinet_netifas() -> Result<Vec<(String, IpAddr)>, Error>
Expand description
Perform a search over the system’s network interfaces using getifaddrs
,
retrieved network interfaces belonging to both socket address families
AF_INET
and AF_INET6
are retrieved along with the interface address name.
§Example
use std::net::IpAddr;
use local_ip_address::list_afinet_netifas;
let ifas = list_afinet_netifas().unwrap();
if let Some((_, ipaddr)) = ifas
.iter()
.find(|(name, ipaddr)| (*name == "en0" || *name == "epair0b") && matches!(ipaddr, IpAddr::V4(_))) {
// This is your local IP address: 192.168.1.111
println!("This is your local IP address: {:?}", ipaddr);
}
Examples found in repository?
examples/show_ip_and_ifs.rs (line 24)
6fn main() {
7 match local_ip() {
8 Ok(ip) => println!("Local IPv4: {}", ip),
9 Err(err) => println!("Failed to get local IPv4: {}", err),
10 };
11
12 match local_ipv6() {
13 Ok(ip) => println!("Local IPv6: {}", ip),
14 Err(err) => println!("Failed to get local IPv6: {}", err),
15 };
16
17 // this is only supported on linux currently
18 #[cfg(target_os = "linux")]
19 match local_broadcast_ip() {
20 Ok(ip) => println!("Local broadcast IPv4: {}", ip),
21 Err(err) => println!("Failed to get local broadcast IPv4: {}", err),
22 };
23
24 match list_afinet_netifas() {
25 Ok(netifs) => {
26 println!("Got {} interfaces", netifs.len());
27 for netif in netifs {
28 println!("IF: {}, IP: {}", netif.0, netif.1);
29 }
30 }
31 Err(err) => println!("Failed to get list of network interfaces: {}", err),
32 };
33}