Reputation: 1753
I have written a program in C which communicates through udp with an Arduino. My question is, how can I "ping" an ip address and only get a 1 or 0 (available or not) in C (unix).
The system("ping xxx.xxx.xxx.xxx");
call doesn't work because it outputs a list...?
Upvotes: 2
Views: 1457
Reputation: 138357
system("ping -c 1 127.0.0.1 > /dev/null");
Should do the trick. -c 1
sends only a single packet. We pipe to /dev/null
as we don't care about the output to stdout (is that the list you refer to?). If you also want to discard stderr, add a 2>&1
to the end. You might also want to limit the response time using -W
.
The call will return an integer representing the success or failure. 0 indicates success, while a non-zero integer represents failure. Here's some sample code: http://ideone.com/cf0eR
Be aware that a failed ping does not guarantee that the device is offline. Although in your controlled environment, it's probably a reasonable thing to expect it to work.
Upvotes: 2
Reputation: 287875
In general, you can not determine whther a network host is up - a member of an IP network is allowed not to send any packets. The best way is to just start communication and use a protocol that requires the contacted machine to answer in any way.
However, if you are sure the machine answers to ping, but not your UDP packets, use ping -c 1 192.0.32.10
. This solution is very brittle though:
Upvotes: 2