0

Sorry for another misleading title, found it hard to describe what it is. I am trying to have the user be able to type something in the console and have it add that to the end of a system() command. For example:

cout << "Input an ip in the form of xx(x).xx(x).xx(x).xx(x)" << endl;
cin >> ipstring;
system("ping");  

Then have ipstring after ping so they user can type in what they want to ping. In java I think it would be something like:

system( "ping" + ipstring )
informative
  • 53
  • 2
  • 13
  • 3
    Be careful with this. What if `ipstring` is `; rm -rf /`? – indiv Apr 14 '15 at 23:45
  • 1
    I accidentaly wiped out my VM disk just a couple of months ago working with some legacy code that heavily used `system`. Seriously do not do that. – sbabbi Apr 14 '15 at 23:58

3 Answers3

1

system() expects a char* as input.

Assuming ipstring is a std::string, you can do this:

system( ("ping " + ipstring).c_str() );

If not, you could use something more like this instead:

std::ostringstream oss;
oss << "ping " << ipstring;
system( oss.str().c_str() );

That being said, you really should not use system() for this. As others have stated, it is an injection attack vector. You should instead use a native API for performing the ping, when available, such as IcmpSendEcho() on Windows. Or a third-party library.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • You can use `system` as long as you [sanitize user input](http://stackoverflow.com/questions/4273074/sanitize-user-input-in-bash-for-security-purposes) first. – indiv Apr 14 '15 at 23:52
  • Agreed. On the other hand, `system()` is spawning a separate process, which may not always be desirable. If there is an API function available to perform the same task, you should use it. – Remy Lebeau Apr 14 '15 at 23:55
0

In C++ it's almost exactly the same thing, assuming ipstring is an std::string:

system(("ping"+ipstring).c_str());

If ipstring is a const char*, then you should convert ping to a std::string first:

system((std::string("ping")+ipstring).c_str());
0

You could use 'sprintf', like so

char to_send[1000];
sprintf(to_send,"ping %s" , ipstring.c_str());
system(to_send)

Assuming your 'ipstring' is an std::string.

Abhishek Vasisht
  • 406
  • 6
  • 18