| 1 | //! A crate for get local ip address, |
| 2 | //! without using `ifconfig` or scanning `network interface` |
| 3 | |
| 4 | use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::netrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/::UdpSocketrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/udp/UdpSocket#; |
| 5 | |
| 6 | /// get the local ip address, return an `Option<String>`. when it fail, return `None`. |
| 7 | pub fn getrust-analyzer cargo local_ipaddress 0.1.3 get().() -> Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#> { |
| 8 | let socket = match UdpSocketrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/udp/UdpSocket#::bindrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/udp/impl#[UdpSocket]bind().("0.0.0.0:0") { |
| 9 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(s) => s, |
| 10 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(_) => return Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#, |
| 11 | }; |
| 12 | |
| 13 | match socket.connectrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/udp/impl#[UdpSocket]connect().("8.8.8.8:80") { |
| 14 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(()) => (), |
| 15 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(_) => return Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#, |
| 16 | }; |
| 17 | |
| 18 | match socket.local_addrrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/udp/impl#[UdpSocket]local_addr().() { |
| 19 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(addr) => return Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(addr.iprust-analyzer cargo core https://github.com/rust-lang/rust/library/core net/socket_addr/impl#[SocketAddr]ip().().to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().()), |
| 20 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(_) => return Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#, |
| 21 | }; |
| 22 | } |