1extern crate regex;
2
3use std::process::Command;
4use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5use regex::Regex;
6
7pub fn get() -> Option<IpAddr> {
8 let output = Command::new("ifconfig")
9 .output()
10 .expect("failed to execute `ifconfig`");
11
12 let stdout = String::from_utf8(output.stdout).unwrap();
13
14 let re = Regex::new(r#"(?m)^.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*$"#).unwrap();
15 for cap in re.captures_iter(&stdout) {
16 if let Some(host) = cap.at(2) {
17 if host != "127.0.0.1" {
18 if let Ok(addr) = host.parse::<Ipv4Addr>() {
19 return Some(IpAddr::V4(addr))
20 }
21 if let Ok(addr) = host.parse::<Ipv6Addr>() {
22 return Some(IpAddr::V6(addr))
23 }
24 }
25 }
26 }
27
28 None
29}
30
31#[cfg(test)]
32mod tests {
33 #[test]
34 fn it_works() {
35 }
36}