c++ – How to scan the network for powered on computers?

Question:

There are computers in local networks and each of them has its own IP address. How to find out, sorting through all the IPs, which computers are connected to the network.

I tried through the PING command, received a response from it and checked it:

string subNet = "192.168.1.";
for(int i = 1; i < 256; i++){
    string network_IP = subNet + to_string(i);
    string request = "ping " + network_IP + " -c 1 > /dev/null"; 
    string result = system(request.c_str()) == 0 ? "true" : "false";
    cout << network_IP << " available: " << result << endl;
}

but this system works for a very long time, how can it be accelerated?

Answer:

the system is running for a very long time

she doesn't work . it is waiting for a response to a ping request. If this host is "live", then the answer arrives almost instantly. If the host does not respond, then the ping utility waits for a timeout. The value of this timeout is set by the "-W" key. Try to specify "-W1" – see the result.

how can i speed it up?

I already said about the timeout. But, this is not a radical remedy. A radical solution would be to write two functions:

  1. Send ICMP Request
  2. Wait for a response to an ICMP request.

Then you send requests in a loop to all addresses of the local network – without (!) Waiting for a response. Inside each ICMP request sent, specify its ID.

Then you wait for a timeout one (!) time. Here is the call loop of your second function. She receives the packet and determines by ID who this answer came from. All this continues timeout. Who managed to send the answer – he is alive. Who did not send – that is not in the network. Thus, the timeout works out only once.

There is another problem: sysadmins, to prevent hacking, often forbid hosts from sending responses to ICMP requests.

As a "fish" for writing these two functions, I recommend using a simple user text .failer on the page https://forum.sources.ru/index.php?showtopic=57566

Scroll to Top