You could download an open source program that does the scanning + connection, like
and modify it to fit your needs,
or connect via existing command line tools, in a script
Regarding counting the number of hops, you can use the traceroute utility, in a script,