How to capture ping return value in C ++

Does anyone know how to capture the ping return value in C ++? According to this link : ping should return 0on success, 1on failure, such as an unknown host, invalid packet size, etc. and 2on an inaccessible host or network.

In C ++, I called ping with system ()for example. int ret = system("ping 192.168.1.5");.

My problem is that the value retis equal to 0or 1. It will never be 2! If I think correctly, this is because this is the return value that I get, these are system functions that return a value, not ping. So how can I get ping return vlaue?

Thanks in advance!

Kampi

Edit: Now I am using this system ("ping 192.169.1.5> ping_res.txt"); but I don’t want to work with files (open and read them), so I want to capture the return value, if possible :)

+3
source share
4 answers

If you use Windows, it is best to use IcmpSendEcho2 to implement the ping functionality in your application.

+6
source

A simple solution would be to output the ping output to a file and read it.

eg.

system("ping 192.169.1.5 > ping_res.txt");

And read ping_res.txtto get the necessary information.

+1
source

man 3 system Linux:


-1 (, fork (2) ) . , wait (2).

man 2 wait Linux:

NULL, wait() waitpid() int, . ( , , wait() wait-pid()!):

WIFEXITED ()
true, , , exit (3) _exit (2) main().

WEXITSTATUS ()
. 8 , exit (3) _exit (2) return main(). , WIFEXITED .

sys/wait.h Linux:

# define WEXITSTATUS(status)    __WEXITSTATUS(__WAIT_INT(status))

/waitstatus.h Linux:

/* If WIFEXITED(STATUS), the low-order 8 bits of the status.  */
#define __WEXITSTATUS(status)   (((status) & 0xff00) >> 8)

, , Linux. HP-UX? , HP-UX. , man 3 system?

, , system sh -c, sh:


:
0 script .
1-125 , .
  127 command_file .
, (. ).

, , , system("exit 203");?

+1

, : , "0 , 1 , , , .. 2 ". , ping . , -, .

, ** open() ** 7 (Echo). , ping . , , -. , , , .

+1

Source: https://habr.com/ru/post/1720148/


All Articles