Skip to content

Concurrent pinging gives spurious results #6

Description

@michael-hartmann

Hello,

I am new to Rust and I am trying to ping multiple IP addresses at the same time using threads. When I use the ping crate sequentially, the result is as expected: IP addresses which are online yield Ok, IP addresses which are not online yield Err. However, when I try to ping multiple addresses concurrently, the behavior is "random", i.e., the return value from ping::ping does not reflect whether the address is available or not.

Minimal Example

Here is a minimal example:

use std::net::IpAddr;
use std::str::FromStr;
use std::thread;
use std::time::Duration;

use ping;

fn is_online(ip: IpAddr) -> bool {
    let timeout = Duration::from_millis(50);
    match ping::ping(ip, Some(timeout), None, None, None, None) {
        Ok(_) => { println!("{}: online", ip); true },
        Err(_) => { println!("{}: offline", ip); false },
    }
}

fn main() {
    let ips = [
        "192.168.178.1", // is available in my network
        "192.168.178.2", // is not available in my network
        "192.168.178.3", // is not available in my network
        "192.168.178.4", // is not available in my network
    ];

    let mut handles = vec![];
    for ip in ips {
        let addr = IpAddr::from_str(ip).unwrap();
        let handle = thread::spawn(move || {
            is_online(addr);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

In my network, only 192.168.178.1 is available, but I see this output

192.168.178.2: online
192.168.178.4: online
192.168.178.3: online
192.168.178.1: online

or also this output:

192.168.178.1: online
192.168.178.2: offline
192.168.178.4: offline
192.168.178.3: offline

Additional Remarks

I have seen the exact same problem when I was using ping with tokio and green threads.

As said, I am new to Rust and maybe the code has some inherent logic error which I don't see. So please be forgiving if this is a stupid question. :-)

Version Information

I am using ping version 0.4.0 with rustc 1.67.1 (d5a82bbd2 2023-02-07).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions