I want to build a code which given an ip-address just prints the finalresult reachable or not. I guess we have to use ping command but am not able to correctly implement it.
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
You could use e.g. popen with the ping command.
Or use the libping library.
Or, assuming some HTTP server is running on the remote machine, issue a
HEAD
HTTP request thru libcurlOr code the low level system calls done by ping. Use strace to find them out.
P.S. some system calls require "root" privilege. This is why
/bin/ping
is setuidWell you'd want to construct a pipe between ping and your program using popen()
(see e.g.: http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html)
Then you need to parse the input appropriately.
Consider the following example program:
On my system it prints:
On my network
192.168.0.1
is my own computer,192.168.0.9
is an address that is not on the network.As you can see you get two different errors depending on if an address can be reached (the first line of output) or not (the second line).
Note that "reachability" on IP networks is kind of tricky to test for.
It's perfectly possible that a server machine is running any number of real services (www, ftp, whatever), but has been configured not to reply to pings since some people do that.
If possible, it's better to just connect like the real service you want to check for.
As others suggested, you can use
popen()
.But remember,
ping
isn't reliable, firewalls can block ICMP echo (which is used by ping) yet the host could be still reachable on specific ports.