system("ping" ) fails!

Hi!
I'm trying to ping a target , and i use
1
2
string pingStr = "ping " + target ;
system( pingStr.c_str());

but, this fails!
Can anyone tell me why this fail ? and How can i make it work ?

Or is it any better and easier way to ping ?
Btw,I've compiled this code on Windows XP SP3.
Thanks in advance,


Vague!
Does it fail to compile (possibly because target is another string literal and you cannot add pointers)
Does it compile and attempts to run and you get a windows error message.

In other words - rephrase your question.
It's compiled but it doesnt work when i run it.
It doesnt work the way it must work.
This simple program works for me.
1
2
3
4
5
6
7
8
9
10
#include <string>
using namespace std;

int main ()
{
  string pingStr = (string)"ping " +"www.yahoo.com" ;
  system( pingStr.c_str());  

}


Post your code let's see what you have
This is entire code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std ;

class Ping{
private:
       string target;
public:
       Ping(){}
       Ping(string _target);
       void setTarget( string _target);
       void startPing();
};
Ping::Ping(string _target) : target( _target){}

void Ping::setTarget( string _target )
{
     this->target = _target ;
}
void Ping::startPing()
{
     cout << "Pinging " << target << endl;
     cout << "Please wait..." << endl ;
     string pingStr = "ping  " + target ;

     int flag = system( pingStr.c_str());
}
int main( void )
{
    Ping p =  Ping();
    p.setTarget( "www.google.com" );
    p.startPing();
    
    system( "PAUSE" );
    return EXIT_SUCCESS ;
}

When i run this code , i got following screen.

http://img717.imageshack.us/img717/1204/20065402.jpg
Last edited on
Looks like you have a network issue or a security issue with your pc or something - I had no problem running your progarm (exactly as you have posted it).

Mind you I'm running Windows 7 - I'm just going to test it on XP


***EDIT - See my next post **
Last edited on
OH - I just realise - You calling the name of your program ping.exe aren't you??

Your working directory is the same as the one your program is in - this means that your program is recursively calling itself - instead of the real ping program.

Rename your program to MyPing.exe and see what happens.
OMG :)
What a stupid mistake :)

Thank you
Never use the system function. It's bad practice and is a huuuge security hole. What happens when someone places the program your calling with system( )? I suppose there might be no way to get arround it if you are using multiple exes in your project. But never use it for something like

system("PAUSE");

it would be so easy for a virus to replace something standard throughout windows computers.
Topic archived. No new replies allowed.