1

I am quite new to C environment. I want to write a program in which i need to add a functionality where I input a an IP address and that function should directly tell me whether this IP address is reachable or not. Any pointers? -Thanks

aragorn ara
  • 165
  • 3
  • 14
  • The beauty of Open Source. [ping source code](http://git.busybox.net/busybox/plain/networking/ping.c). – kaylum Sep 11 '15 at 06:22
  • 1
    Btw, with Firewalls doing all kind of crazy filtering nowadays, no method is really reliable except trying to make exactly the connection you need and see whether it succeeds. –  Sep 11 '15 at 06:24

2 Answers2

2

Do you want to use the same methods as the actual ping command, or something simpler? If you want something simpler, just try to do a TCP connection to the system using a random port number, you will get different errors if the system is not reachable or if it is reachable but no one is listening on that port (or you get a connection, which you then promptly close).

If using TCP connections, you might get a long (many seconds) timeout though, as TCP tries and retries to connect. Also, if the system is reachable such a probe might be seen as an intrusion attempt, while a ping (ICMP echo request) is not.

Another caveat is that both TCP connection attempts and ICMP echo request might be stopped anywhere from your system to the remote system by a firewall.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Well I figured out the issue, it was with my linux flavor. Generally it should check for timeout event after certain time but in my machine I need to explicitly mention it.

Well, I figured what was the issue. Apparently for few flavors of linux you need to explicitly mention -w filer. so my solution is :

Well, I figured what was the issue. Apparently for few flavors of linux you need to explicitly mention -w filer. so my solution is :

if ( system("ping -c1 128.205.159.60 -w 2 ") == 0)
    {
        printf ("\n Exists");
    }
    else
    {   printf ("\n Not reachable ");
    }

Thanks everyone for your input. :)

aragorn ara
  • 165
  • 3
  • 14
  • 1
    This is the worst possible "solution". You don't spawn an external tool without a **strong** need -- it creates all kinds of problems (depending on the existence of the tool, and, in your case, proper `$PATH` setting) *and* wastes resources for forking etc. –  Sep 11 '15 at 06:32
  • @FelixPalmen: Could you please provide me reason behind it. I am quite new in this domain so I can learn from it. – aragorn ara Sep 11 '15 at 06:34
  • Sorry, just decided to add some reasoning -- at a minimum, you'd have to check the return value of `system()` for `-1`to catch cases where trying to execute ping failed. Better just do the ICMP echo request in your code. –  Sep 11 '15 at 06:34
  • Ohh ok. I will try to work on it. Thanks for sharing this info. I will look into ICMP echo request and try to work on return code form it. – aragorn ara Sep 11 '15 at 06:40