Hasitha Shan
Hasitha Shan

Reputation: 2980

Execute a recursive ping shell command programmatically

I have a requirement of obtaining the IP addresses of all devices within LAN programatically. This I was planning to implementing by issuing the following shell command through c using the system().

for ip in $(perl -e '$,="\n"; print 1 .. 254;') ; do ping -t 1 -c 1 192.168.1.$ip>/dev/null; [ $? -eq 0 ] && echo "192.168.1.$ip UP" || : ; done

However it does not quite work. As in first it doesn't print out the result on the terminal it should if were to run it directly as a shell command in the terminal, and also I want to obtain the results that gets printed on the terminal to the program so that I can work with it.

I was at this for quite some time and could not get it working. I would really be grateful if you experts could give a code segment example, any reference or any methodology to get through this issue.

Upvotes: 0

Views: 280

Answers (2)

gat
gat

Reputation: 2990

It would be easier to write a shell script which takes the ip as a parameter. And then from your system call you could simply run the shell script.

Having said that, the neater way would be to actually use library functions to achieve what you are trying to do.

Upvotes: 1

david.pfx
david.pfx

Reputation: 10863

What you are trying to do is a kind of port scanning on your local LAN. This is quite a difficult thing to do well, involving a number of different potential error conditions. It can also be quite slow, so that using parallelism is highly desirable.

Unless this is an important technology to master, I would agree with using a third party solution and not try to write your own. However, Ping is not necessarily the proper choice.

The standard tool for this purpose is NMAP. It can do what you want, and heaps of other things besides. Link here: http://nmap.org/.

Upvotes: 3

Related Questions