How to work with system calls in linux using C++

I am doing this program where I am using system("ping hostip"), instead of displaying the ping info I want to store rather the host is reachable or not. For Example, system("ping") it is not reachable so "false" should be stored in hostreachable. This is the only way I know how to tell if a host is reachable by using ping. By any chance can any one tell me another way to do this or tell me how to get the information that is needed from ping.

Thanks in Advance,
Tiffanie N. Jones
Last edited on
If you have to use a system() call, I'd recommend
system("ping -c 1 IP | grep 'time=[0-9.]\\\+ ms' | wc -l > pingres.txt");
Then reading pingres.txt's contents. However! This solution is anything but professional. I'd suggest forking a child for ping (running it by exec() ), and creating pipes to read from it's stdout.
Last edited on
Personally I would look at the source code for the ping command and write a stripped down version of it myself. All you need to do is open an ICMP socket, send the ICMP echo request and read the response.

I had to do this for an analysis program on a slightly larger scale. If you are looking to send this request to many hosts, then it is easiest to use NMAP to ping the list. It outputs a line like this:

> nmap -sP -n IP1 IP2 IP3 IP4
Starting Nmap 4.53 ( ) at 2008-10-23 09:22 EDT
Host IP1 appears to be up.
Host IP3 appears to be up.
Nmap done: 1 IP address (1 host up) scanned in 0.030 seconds

If you ignore the first line and the last line, then you have a list of all of the IPs that are up and in a very-easy-to-parse fashion. You can use gryphon's output trick to read it into your program.

If you want to follow jsmith's advice, then I recommend reading Beej's guide to network programming:

It will give you a basic network programming primer. From there you could read this:

Which shows how to create a very basic ping implementation that you could use for this purpose.

If you get it implemented, post the results here so other people could use it; I have a feeling lots of people would like that :-)
Also, if you are looking for a way to just read the output of the system() call, read this:

It explains near the bottom how to use system and pipe redirection to grab the output.
Topic archived. No new replies allowed.