Giter VIP home page Giter VIP logo

local-ip-address's Introduction

local-ip-address

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

Crates.io Documentation Build Clippy Formatter

Usage

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

use local_ip_address::local_ip;

fn main() {
    let my_local_ip = local_ip().unwrap();

    println!("This is my local IP address: {:?}", 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:

use local_ip_address::list_afinet_netifas;

fn main() {
    let network_interfaces = list_afinet_netifas().unwrap();

    for (name, ip) in network_interfaces.iter() {
        println!("{}:\t{:?}", name, ip);
    }
}

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 Uses of getifaddrs to retrieve network interfaces
Windows Consumes Win32 API's to retrieve the network adapters table

Operating System Support

Current supported platforms include:

  • Linux (requires at least v0.1.0);
  • macOS (requires at least v0.1.0);
  • Windows (requires at least v0.3.0);
  • Other BSD-based (requires at least v0.5.0); including:
    • FreeBSD
    • OpenBSD
    • NetBSD
    • DragonFly

Please note that we only test the BSD implementation of this on macOS and FreeBSD, under the assumption that other BSD-based systems will behave similarly. If you have any complications using this library on the other BSD-based, please create an issue.

Release

In order to create a release you must push a Git tag as follows

git tag -a <version> -m <message>

Example

git tag -a v0.1.0 -m "First release"

Tags must follow semver conventions Tags must be prefixed with a lowercase v letter.

Then push tags as follows:

git push origin main --follow-tags

Contributing

Every contribution to this project is welcome. Feel free to open a pull request, an issue or just by starting this project.

License

Distributed under the terms of both the MIT license and the Apache License (Version 2.0)

local-ip-address's People

Contributors

alexkrob avatar bitcapybara avatar cgzones avatar d1plo1d avatar dependabot[bot] avatar estebanborai avatar galaxyshard avatar github-actions[bot] avatar hummingly avatar jacobtread avatar jsydliuqing avatar justbobinaround avatar meowtec avatar nashley avatar nicguzzo avatar tudyx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

local-ip-address's Issues

[linux] ipv6 address reported on wrong (moving) interface alias

Initial state:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.137.0.41  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::216:3eff:fe5e:6c00  prefixlen 64  scopeid 0x20<link>

A loop on local_ip_address::list_afinet_netifas().iter() reports both addresses as expected:

 lo - 127.0.0.1
 eth0 - 10.137.0.41
 ...
 lo - ::1
 eth0 - fe80::216:3eff:fe5e:6c00

Now it I add another IP using a alias, using ifconfig eth0:1 192.168.132.191, which in ifconfig output shows as expected:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.137.0.41  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::216:3eff:fe5e:6c00  prefixlen 64  scopeid 0x20<link>
        ether 00:16:3e:5e:6c:00  txqueuelen 1000  (Ethernet)
        RX packets 3086518  bytes 2499552776 (2.3 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1966650  bytes 245416649 (234.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.132.191  netmask 255.255.255.0  broadcast 192.168.132.255
        ether 00:16:3e:5e:6c:00  txqueuelen 1000  (Ethernet)

... then the same loop wrongly reports the IPv6 address on the new alias:

 lo - 127.0.0.1
 eth0 - 10.137.0.41
 eth0:1 - 192.168.132.191
 ...
 lo - ::1
 eth0:1 - fe80::216:3eff:fe5e:6c00

Why local_ip() return IpAddr?

According to documentation, local_ip() function retrieves the local IPv4 address (and local_ipv6() retrieves the local IPv6 address), but why inside return type is general IpAddr enum instead of Ipv4Addr and Ipv6Addr? I think it's confusing and inconvenient for user.

SIGSEGV if tun device is present

The list all interface and IP program crashes with 'cargo run' terminated by signal SIGSEGV (Address boundary error) if I create a tun device using sudo ip tuntap add tun0 mode tun.
code:

use local_ip_address::list_afinet_netifas;

fn main() {
    let network_interfaces = list_afinet_netifas().unwrap();

    for (name, ip) in network_interfaces.iter() {
        println!("{}:\t{:?}", name, ip);
    }
}

Unexpected "\0" in the network interface name

Environment

  1. Linux version: windows11 wsl2
$ uname -a
Linux bitcapybara 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 GNU/Linux
  1. ip
$ ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:2b:e5:eb brd ff:ff:ff:ff:ff:ff
    inet 172.x.x.x/20 brd 172.x.x.x scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::x:x:x:x/64 scope link
       valid_lft forever preferred_lft forever

Code

use local_ip_address::list_afinet_netifas;

fn main() {
    let ifas = list_afinet_netifas().unwrap();
    println!("{:?}", ifas);
}

Expected output

$ cargo run
[("lo", 127.0.0.1), ("eth0", 172.x.x.x), ("lo", ::1), ("eth0", fe80::x:x:x:x)]

Actual output

$ cargo run
[("lo\0", 127.0.0.1), ("eth0\0", 172.x.x.x), ("lo\0", ::1), ("eth0\0", fe80::x:x:x:x)]

Conclusion

As shown above, the network interface name in all output has an extra "\0". Is this normal? And how can I solve it?

Hope to support FreeBSD OS

My project uses the local-ip-address dependency library and it runs normally. Thank you very much for your creation;

But now I have a problem when I want to port the project to the FreeBSD platform. The local-ip-address library cannot be compiled on the FreeBSD12 platform;

I have seen in the release of this project that the FreeBSD system is not supported,
But I still want to know if the author has plans to support FreeBSD OS in the future?

Thanks again for your work!

The following errors I encountered when compiling under the FreeBSD12 platform, I hope to help you

error[E0308]: mismatched types
--> /root/.cargo/registry/src/github.com-1285ae84e5963aae/local-ip-address-0.4.4/src/lib.rs:86:22
|
86 | pub fn local_ip() -> Result<IpAddr, Error> {
| -------- ^^^^^^^^^^^^^^^^^^^^^ expected enum Result, found ()
| |
| implicitly returns () as its body has no tail or return expression
|
= note: expected enum Result<IpAddr, Error>
found unit type ()

For more information about this error, try rustc --explain E0308.
error: could not compile local-ip-address due to previous error
warning: build failed, waiting for other jobs to finish...
error: build failed

MacOS bug on 0.5.0

When using it on 0.4.9 it works perfectly fine, but when updating to 0.5.0 I get 127.0.0.1 on MacOS. Still works on Linux and Windows.

MacBook Pro running MacOS Ventura.

failed to resolve: use of undeclared crate or module `env`

System : macOS

error[E0433]: failed to resolve: use of undeclared crate or module `env`
   --> /Users/swithun/.cargo/registry/src/github.com-1ecc6299db9ec823/local-ip-address-0.5.1/src/lib.rs:179:41
    |
179 |         Err(Error::PlatformNotSupported(env::consts::OS.to_string()))
    |                                         ^^^ use of undeclared crate or module `env`

error[E0433]: failed to resolve: use of undeclared crate or module `env`
   --> /Users/swithun/.cargo/registry/src/github.com-1ecc6299db9ec823/local-ip-address-0.5.1/src/lib.rs:194:37
    |
194 |     Err(Error::PlatformNotSupported(env::consts::OS.to_string()))
    |                                     ^^^ use of undeclared crate or module `env`

For more information about this error, try `rustc --explain E0433`.
error: could not compile `local-ip-address` due to 2 previous errors

Cannot compile for Windows MSVC on Linux

When I try to compile via cargo build --target x86_64-pc-windows-msvc I get this error. Other crates compiled successfully.

 --> /home/msenol/.cargo/registry/src/github.com-1ecc6299db9ec823/local-ip-address-0.4.4/src/windows.rs:2:5
  |
2 |     windows::include_bindings!();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in the macro `::std::include` (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

error: could not compile `local-ip-address`


Feature Request: Determining Netmask

This may be a feature already, I just couldn't find anything in the docs. Is there anyway to get the netmask of the ip? I am currently using this for a project to determine the UDP broadcast ip:

10  .0   .0   .5    // ip
255 .255 .255 .0    // netmask
----------------
10  .0   .0   .255    // broadcast

In most networks, I can assume the broadcast ip is just the last digit changed to 255, however if the netmask is changed, then so is the broadcast:

10  .0   .0   .5    // ip
255 .255 .0   .0    // netmask
----------------
10  .0   .255 .255    // broadcast

Windows Support

Currently we only have support for Unix systems but it would be awesome to have support on Windows systems as well.

error: build failed

Compiling local-ip-address v0.5.2
error[E0599]: no variant or associated item named LookupTable found for enum RtmF in the current scope
--> /root/.cargo/registry/src/github.com-1285ae84e5963aae/local-ip-address-0.5.2/src/linux.rs:39:43
|
39 | rtm_flags: RtmFFlags::new(&[RtmF::LookupTable]),
| ^^^^^^^^^^^ variant or associated item not found in RtmF

error[E0599]: no variant or associated item named LookupTable found for enum RtmF in the current scope
--> /root/.cargo/registry/src/github.com-1285ae84e5963aae/local-ip-address-0.5.2/src/linux.rs:195:43
|
195 | rtm_flags: RtmFFlags::new(&[RtmF::LookupTable]),
| ^^^^^^^^^^^ variant or associated item not found in RtmF

error[E0599]: no variant or associated item named LookupTable found for enum RtmF in the current scope
--> /root/.cargo/registry/src/github.com-1285ae84e5963aae/local-ip-address-0.5.2/src/linux.rs:256:43
|
256 | rtm_flags: RtmFFlags::new(&[RtmF::LookupTable]),
| ^^^^^^^^^^^ variant or associated item not found in RtmF

For more information about this error, try rustc --explain E0599.
error: could not compile local-ip-address due to 3 previous errors
warning: build failed, waiting for other jobs to finish...
error: build failed
bash-5.1# mc

Additional interface info?

Feature request

Do you think it would be possible add getting additional interface information such as subnet mask and the broadcast address?

Incorrect local IP address got on Windows

Running test functions on Windows 10 on a NUC8 machine got incorrect local IP address as follows (the ifas value is also printed out):

ifas is [("Ethernet", fe80::5968:d94e:958e:1e5c), ("Ethernet", 169.254.30.92), 
("VirtualBox Host-Only Network", fe80::a095:abb9:e1b9:5bd6), ("VirtualBox Host-Only Network", 192.168.56.1),
 ..., 
("Wi-Fi", fe80::1d7e:8c98:843:b568), ("Wi-Fi", 192.168.0.13), 
("Bluetooth Network Connection", fe80::585e:ad7:2517:b448), ("Bluetooth Network Connection", 169.254.180.72), 
("Loopback Pseudo-Interface 1", ::1), ("Loopback Pseudo-Interface 1", 127.0.0.1)]

test tests::find_network_interfaces ... Windows 'local_ip': 169.254.30.92
ok
test tests::find_local_ip ... ok

Seems like Wi-fi should be used in this case, but not sure if it's a common issue.

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: LocalIpAddressNotFound',

If i run my rust program in virtual network space, will issue the following error message:
thread 'main' panicked at 'called Result::unwrap() on an Err value: LocalIpAddressNotFound', measure-device/src/main.rs:33:52
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

My rust code as following:
in src/main.rs

fn main() {
    let my_local_ip = local_ip_address::local_ip().unwrap();
    println!("This is my local IP address: {:?}", my_local_ip);
}
local_ip_address's version is 0.6.0;

You can reproduce it as the following steps:

  1. In ubuntu 20.04 OS, create virtual network space.
sudo ip netns add ns0
sudo ip l add br0 type bridge
sudo ip l set br0 up
sudo ip l add veth0 type veth peer name veth0br
sudo ip l set veth0 netns ns0
sudo ip netns exec ns0 ip a add 192.168.80.10/24 dev veth0
sudo ip netns exec ns0 ip l set veth0 up
sudo ip l set veth0br master br0
sudo ip l set veth0br up
  1. Run rust demo program in ns0
sudo ip netns exec ns0 target/debug/your-rust-demo

Here, the rust demo program will report the error message.

Windows 10 Chinese version is not supported

I am using the Chinese version of windows 10, when I use this library, the program terminates and throws an error UnsupportPlatform(Windows)

I quickly browsed the library code and found that English hard-coded query conditions are used here Ethernet :
https://github.com/EstebanBorai/local-ip-address/blob/main/src/lib.rs#L111

On Windows 10 Chinese operating system, the name will be 以太网 .

Similar problems may exist on windows systems that use other languages. Is there a better solution?

Misleading error message when using non-`en0` interface on macOS

Calling local_ip() on macOS when using e.g. en1 instead of en0 (with the latter not being assigned an IP at all) yields the following, slightly misleading error message:

PlatformNotSupported("macos")

Perhaps the library could try en0, en1, ... in order until it finds an IP address and, if not, throw an error along the lines of "No interface with an IP address found"?

Use `std::alloc::alloc` instead of `libc::malloc`

The libc::malloc implementation doesn't respect the required alignment of different data types, and on machines where malloc returns addresses that are not aligned enough, this might cause undefined behaviour.

Is there a specific reason why libc::malloc is used instead of the standard library's implementation?

Release

A number of dependencies have been updated since v0.4.4.
Could a new patch release be made so newer versions of these dependencies can be used?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.