5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rust]自身のIPアドレスを取得

Last updated at Posted at 2021-07-01

表題の通り。

Windowsとそれ以外で使用するクレートを変えます。windows版pnetの場合、特定のライブラリを入れたりアプリケーションのインストールを要求されたりと面倒だったため。

それぞれis_XXX系のメソッドで取得する内容を変更できます。

You must have WinPcap or npcap installed (tested with version WinPcap 4.1.3) (If using npcap, make sure to install with the "Install Npcap in WinPcap API-compatible Mode")
https://github.com/libpnet/libpnet

Cargo.toml

[target.'cfg(unix)'.dependencies]
pnet = "*"
[target.'cfg(windows)'.dependencies]
ipconfig = "*"

main.rs

#[cfg(target_os = "windows")]
fn get_ip_list() -> Vec<String> {
    use ipconfig;
    let mut ips: Vec<String> = Vec::new();
    match ipconfig::get_adapters() {
        Ok(adapters) => {
            for adapter in adapters {
                if adapter.oper_status() == ipconfig::OperStatus::IfOperStatusUp {
                    for address in adapter.ip_addresses() {
                        if !address.is_loopback() && address.is_ipv4() {
                            ips.push(address.to_string());
                        }
                    }
                }
            }
        }
        _ => {}
    }
    ips
}

#[cfg(not(target_os = "windows"))]
fn get_ip_list() -> Vec<String> {
    use pnet::datalink;
    let mut ips: Vec<String> = Vec::new();
    for interface in datalink::interfaces() {
        // 空ではなく、動作中である。
        if !interface.ips.is_empty() && interface.is_up() {
            for ip_net in interface.ips {
                // ループバックでなく、ipv4である
                if ip_net.is_ipv4() && !ip_net.ip().is_loopback() {
                    ips.push(ip_net.ip().to_string());
                }
            }
        }
    };
    ips
}

fn main() {
    println!("{:?}", get_ip_list());
}

結果

使用可能なIPの一覧が配列で表示されます。

["192.168.11.XXX", "10.XX.XX.XX"]
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?