1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*!
# Local IP Address

Retrieve system's local IP address and Network Interfaces/Adapters on
Linux, Windows, and macOS (and other BSD-based systems).

## Usage

Get the local IP address of your system by executing the `local_ip` function:

```rust
use local_ip_address::local_ip;

let my_local_ip = local_ip();

if let Ok(my_local_ip) = my_local_ip {
    println!("This is my local IP address: {:?}", my_local_ip);
} else {
    println!("Error getting local IP: {:?}", my_local_ip);
}
```

Retrieve all the available network interfaces from both, the `AF_INET` and
the `AF_INET6` family by executing the `list_afinet_netifas` function:

```rust
use local_ip_address::list_afinet_netifas;

let network_interfaces = list_afinet_netifas();

if let Ok(network_interfaces) = network_interfaces {
    for (name, ip) in network_interfaces.iter() {
        println!("{}:\t{:?}", name, ip);
    }
} else {
    println!("Error getting network interfaces: {:?}", network_interfaces);
}
```

Underlying approach on retrieving network interfaces or the local IP address
may differ based on the running operative system.

OS | Approach
--- | ---
Linux | Establishes a Netlink socket interchange to retrieve network interfaces
BSD-based & Android | Uses of `getifaddrs` to retrieve network interfaces
Windows | Consumes Win32 API's to retrieve the network adapters table

Supported BSD-based systems include:
  - macOS
  - FreeBSD
  - OpenBSD
  - NetBSD
  - DragonFly
*/

use std::net::IpAddr;

mod error;

pub use error::Error;

#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "linux")]
pub use crate::linux::*;

#[cfg(any(
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    target_os = "macos",
    target_os = "android",
    target_os = "ios",
))]
pub mod unix;

#[cfg(any(
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    target_os = "macos",
    target_os = "android",
    target_os = "ios",
))]
pub use crate::unix::*;

#[cfg(target_family = "windows")]
pub mod windows;
#[cfg(target_family = "windows")]
pub use crate::windows::*;

/// Retrieves the local IPv4 address of the machine in the local network from
/// the `AF_INET` family.
///
/// A different approach is taken based on the operative system.
///
/// For linux based systems the Netlink socket communication is used to
/// retrieve the local network interface.
///
/// For BSD-based systems the `getifaddrs` approach is taken using `libc`
///
/// For Windows systems Win32's IP Helper is used to gather the Local IP
/// address
pub fn local_ip() -> Result<IpAddr, Error> {
    #[cfg(target_os = "linux")]
    {
        crate::linux::local_ip()
    }

    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
    ))]
    {
        let ifas = crate::unix::list_afinet_netifas_info()?;

        ifas.into_iter()
            .find_map(|ifa| {
                if !ifa.is_loopback && ifa.addr.is_ipv4() && !ifa.is_mobile_data() {
                    Some(ifa.addr)
                } else {
                    None
                }
            })
            .ok_or(Error::LocalIpAddressNotFound)
    }

    #[cfg(target_os = "windows")]
    {
        use windows_sys::Win32::Networking::WinSock::AF_INET;

        let ip_addresses = crate::windows::list_local_ip_addresses(AF_INET)?;

        ip_addresses
            .into_iter()
            .find(|ip_address| matches!(ip_address, IpAddr::V4(_)))
            .ok_or(Error::LocalIpAddressNotFound)
    }

    // A catch-all case to error if not implemented for OS
    #[cfg(not(any(
        target_os = "linux",
        target_os = "windows",
        target_os = "macos",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "android",
        target_os = "ios",
    )))]
    {
        Err(Error::PlatformNotSupported(
            std::env::consts::OS.to_string(),
        ))
    }
}

/// Retrieves the local IPv6 address of the machine in the local network from
/// the `AF_INET6` family.
///
/// A different approach is taken based on the operative system.
///
/// For linux based systems the Netlink socket communication is used to
/// retrieve the local network interface.
///
/// For BSD-based systems the `getifaddrs` approach is taken using `libc`
///
/// For Windows systems Win32's IP Helper is used to gather the Local IP
/// address
pub fn local_ipv6() -> Result<IpAddr, Error> {
    #[cfg(target_os = "linux")]
    {
        crate::linux::local_ipv6()
    }

    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
    ))]
    {
        let ifas = crate::unix::list_afinet_netifas_info()?;

        ifas.into_iter()
            .find_map(|ifa| {
                if !ifa.is_loopback && ifa.addr.is_ipv6() && !ifa.is_mobile_data() {
                    Some(ifa.addr)
                } else {
                    None
                }
            })
            .ok_or(Error::LocalIpAddressNotFound)
    }

    #[cfg(target_os = "windows")]
    {
        use windows_sys::Win32::Networking::WinSock::AF_INET6;

        let ip_addresses = crate::windows::list_local_ip_addresses(AF_INET6)?;

        ip_addresses
            .into_iter()
            .find(|ip_address| matches!(ip_address, IpAddr::V6(_)))
            .ok_or(Error::LocalIpAddressNotFound)
    }

    // A catch-all case to error if not implemented for OS
    #[cfg(not(any(
        target_os = "linux",
        target_os = "windows",
        target_os = "macos",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "android",
        target_os = "ios",
    )))]
    {
        Err(Error::PlatformNotSupported(
            std::env::consts::OS.to_string(),
        ))
    }
}

// A catch-all function to error if not implemented for OS
#[cfg(not(any(
    target_os = "linux",
    target_os = "windows",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    target_os = "android",
    target_os = "ios",
)))]
pub fn list_afinet_netifas() -> Result<Vec<(String, IpAddr)>, Error> {
    Err(Error::PlatformNotSupported(
        std::env::consts::OS.to_string(),
    ))
}

mod tests {
    #[allow(unused_imports)]
    use super::*;

    #[test]
    #[cfg(target_os = "linux")]
    fn find_local_ip() {
        let my_local_ip = local_ip();

        assert!(matches!(my_local_ip, Ok(IpAddr::V4(_))));
        println!("Linux 'local_ip': {:?}", my_local_ip);
    }

    #[test]
    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
    ))]
    fn find_local_ip() {
        let my_local_ip = local_ip();

        assert!(matches!(my_local_ip, Ok(IpAddr::V4(_))));
        println!("Unix 'local_ip': {:?}", my_local_ip);
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn find_local_ip() {
        let my_local_ip = local_ip();

        assert!(matches!(my_local_ip, Ok(IpAddr::V4(_))));
        println!("Windows 'local_ip': {:?}", my_local_ip);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn find_network_interfaces() {
        let network_interfaces = list_afinet_netifas();

        assert!(network_interfaces.is_ok());
        assert!(!network_interfaces.unwrap().is_empty());
    }

    #[test]
    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly",
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
    ))]
    fn find_network_interfaces() {
        let network_interfaces = list_afinet_netifas();

        assert!(network_interfaces.is_ok());
        assert!(!network_interfaces.unwrap().is_empty());
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn find_network_interfaces() {
        let network_interfaces = list_afinet_netifas();

        assert!(network_interfaces.is_ok());
        assert!(!network_interfaces.unwrap().is_empty());
    }
}