Pinging from a C/C++ program - c++

I want to write a C or C++ program, that given an IP address, Pings it and then performs further action based on whether the Ping was successful or not.
How to do this?

Have a blast at The Ping Page, which has a link to full source on the original Unix ping(8).

EDIT I saw after I posted, you are on Ubuntu. However someone searching this question may still find these links helpful for Windows.
Ping: Raw Sockets Method: http://tangentsoft.net/wskfaq/examples/rawping.html
Implementing Internet Pings Using Icmp.dll: http://support.microsoft.com/default.aspx?scid=kb;en-us;170591
IcmpSendEcho Function: http://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx
Ping for Windows: http://www.codeproject.com/KB/IP/winping.aspx

This post is old but I think the following link will help future people lookign for a good explanation on how to create a Ping request.
Deconstructing Ping with C and NodeJS

#include <iostream>
using namespace std;
int main() {
int x = system("ping -c1 -s1 8.8.8.8 > /dev/null 2>&1");
if (x==0){
cout<<"success";
}else{
cout<<"failed";
}
replace 8.8.8.8 from your IP Address

Related

ssh remote login to server using system(char * command), and excute commands?

Someone familiar with SSH and System(const char * command) to execute shell command!??
Am trying to remotely login to multiple servers/machines from my C++ code, and i have to execute some commands remotely. To the best of my experience, i decided to use ssh. But, now i want to load and send all my commands through the System(const char * command). pls see my code below..
#include "all my headers"
int main()
{
system("ssh 172.10.10.1");//login to server_one, password=123
system("ssh 172.10.10.2");//login to server_two, password=1234
system("ssh 172.10.10.3");//login to server_three,password=12345
system("ssh 172.10.10.4");//login to server_four, password=123456
return 0;
}
Now,my Question is:
can i load and send the remote_ip of the servers and password at the
same time, something like: system("ssh 172.10.10.4 ,123456")
password=123456? if yes, how?
if am done with (1) above, i will have another question. thanks.
Calling system("ssh ...") will ONLY work if you have set up public keys for the machine you want to log in on.
The reason is that the system() does not allow you to interact with the process you started, it will just spawn a new shell and pass the relevant string to the shell for execution, and ssh does not itself have a way to pass the password to the application, you have to actually type it in (or send it to the stdin side of ssh if you use popen - but I would really suggest that public keys are the right way to go in an automated system).
If you still need to interact with the created process, you will need to use something like popen, which will allow you to read stdout or write to stdin on the - or even pipe() and fork() if you need the ability to do stuff to both stdin and stdout.

DHCP client information request

I am calling the DhcpGetClientInfo function from Windows DHCP Server Management API. Below is a segment of code where I query the DHCP server(in my case a Raspberry Pi) for a specific client's general information. The necessary header files have been included and the program builds fine with no compile time errors.
int a;
DHCP_SEARCH_INFO SearchInfo;
DHCP_CLIENT_INFO* ClientInfo;
// Search criteria
SearchInfo.SearchType = DhcpClientIpAddress;
SearchInfo.SearchInfo.ClientIpAddress = inet_addr("10.10.10.144");
a = DhcpGetClientInfo(L"10.10.10.1", &SearchInfo, &ClientInfo);
if(a != ERROR_SUCCESS){
std::ofstream outputFile("C:\\Temp\\TestX\\log4.txt");
outputFile << a;
}
However, the function fails and returns error number #1722 which does not appear in the DHCP Server Management API Error Codes here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363378(v=vs.85).aspx
I cannot find any information on said error. Has anyone any experience to help me out here. Your help would be greatly appreciated.
Error 1702: RPC_S_SERVER_UNAVAILABLE: The RPC server is unavailable.
Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681386%28v=vs.85%29.aspx

Print from c++ file running on postgresql

I am running some C++ code in postgresql. I am trying to print some output to keep track of the execution, but no result. Is there anything I need to add somewhere to enable printf command to work? I am adding the below mentioned files in my code:
#include "postgres.h"
#include <math.h>
#include <limits.h>
#include <inttypes.h>
What I am trying to print:
printf("abc");
Any help would be greatly appreciated, as I have been trying to get some output for the past 2 days. Thanks!
Edit : I am running the postgresql server using SSH. Let me know via comments if any more information is needed.
You need to use PostgreSQL's build-in logging system: http://www.postgresql.org/docs/current/static/error-message-reporting.html
From the reference:
elog(INFO, "count=%d", count);
The log level has to match the level you've configured PostgreSQL to write to its log file.
printf("abc"); will try to write to stdout, but normally Postgresql server runs as a daemon, which means it will close stdout, that is why you cannot see that string at the standard output.
You should use the error report facilities offered by Postgresql to output those message to Postgresql log file, as pointed out by #rygvis.
you can use fprintf(stderr, "abc\n"); instead of printf("abc");

Piping output from one program to another not working for this particular program

I expect this is a basic question, but I haven't been able to find an answer.
I'm building a web server in C++, and in order to help me visualise the system as it's running I'm building a separate program to do the visualisation. The web server will inform the visualiser of its current state by printing statements to stdout that are piped into the visualiser, which will parse the input and render a nice schematic view of the whole system along with various stats. The visualiser will be written in Python.
To check that I understand how piping works I created two simple programs:
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!\n";
return 0;
}
, and
#include <iostream>
using namespace std;
int main() {
char buf[128];
while (!cin.eof()) {
cin.getline(buf, 128, '\n');
cout << "Received line: " << buf << "\n";
}
return 0;
}
This works as expected when I execute the command
./one | ./two
However, when I run my web server like so:
./aril | ./two
I get no output at all.
Running the server on its own produces output like the following:
Spawning handlers
Waiting for HTTP clients
Server: got connection from 127.0.0.1, port 52168
Connection timed out
(Obviously that isn't actually the kind of output I'll be passing to the visualiser -- it will need a more easily parse-able syntax).
Possibly relevant info:
The web server is divided into two processes: aril and arild. aril runs with root privileges, whereas arild doesn't. Both processes print to stdout using std::cout.
I can't think of any reason why this isn't working.
EDIT:
The solution, it turns out, is simply to explicitly flush the output. Should have been the first thing I tried really..
Your web server is printing in STDERR while in two you are reading from STDIN. So it'll not work.
Change ./aril | ./two to
./aril 2>&1 | ./two
This will redirect all the STDERR and STOUT of aril to STDOUT and thus two will be able to read it.
It is possible that aril detects if its output is piped (see fstat() and this thread http://cboard.cprogramming.com/cplusplus-programming/73909-prevent-piping.html for details) and switches to silent mode, i.e does not produce any output. Try piping to something else, cat maybe, and see if it produces an output.
I think your programs are designed to work as pairs, but not interchangeably. ./one | ./two are an example of piping, but ./aril is expecting to communicate with ./arild via sockets. It probably doesn't make sense to mix ./aril | ./two.

Enum USB devices in Linux/C++

Im writing IO routines for a linux device that will have various and changing USB devices connected to it. To this end I need to be able to figure out which device is connected to which port so I can open it with the correct software. Something akin to 'udevinfo' would be ideal but I have no idea how to start in writing such.
Suggestions on c++ apis to read?
Take a look at libudev++. It seems to be what you're looking for.
See libusb's libusb_get_device_list, libusb_get_bus_number, libusb_get_device_address.
GIO should help you in that. Connecting to the volume-added and volume-removed signals will alert your program to any storage device added or removed from the system. If you do not need the level of control provided by GIO, you can use libudev++ which provided a high level wrapper over GIO.
i don't know what kind of information you need, but you could just go through /sys/bus/usb?
I ended up using a BASH solution in the chkconfig file. I walk through all ttyUSB entries and look at the driver info for each:
USB_ID=`egrep -i "mct u232|pl2303|keyspan" -m 1 /proc/tty/driver/usbserial | awk '{ printf( "$d", $1 )}'`
if [ -z $USB_ID ]
then
echo $echo_n "No USB serial adapter found.";
exit 1
fi
More recent solution:
Iterate over these file system directories:
/dev/serial/by-id
/dev/snd/by-id
/dev/disk/by-id
/dev/input/by-id
/dev/v4l/by-id
depending on what device class you are looking for.
For example, finding the serial port for my Arduino Nano:
#include <filesystem>
#include <string>
const std::string path = "/dev/serial/by-id";
for( const auto & file : std::filesystem::directory_iterator( path ) )
{
const std::string s = "NANO_33_IoT";
if( file.path().generic_string().find(s) )
{
return file.path();
}
}