0

I want to set default deadline for ping in some settings file or so. My program hangs when trying to connect to non-pinging ip address.

In terminal I can call "ping 123.0.0.1 -w 5" and it wont last forever, but I can't set any deadline in code.

ehrid
  • 95
  • 8

1 Answers1

3

Shell Solution:

In your .bashrc add the following:

function ping {
    /bin/ping $@ -w5
}

This will create a wrapper function, which will set the timeout to 5 seconds for all calls to ping

Note: The version above will overwrite a -w param used on command line. If you still want to be able to overwrite the default timeout via the command line than place the -w5 before the $@:

function ping {
    /bin/ping -w5 $@
}

Pure C solution:

I won't give an full example here for brevity. You may find one here for example. In the given example, you'll have to replace the recvfrom() call which reads the ICMP response and may block by a select() or poll() call with a timeout.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Good one. Note that if you ever want to run the default ping command, then you will need to use `\ping`. – fedorqui Aug 09 '13 at 09:25
  • @nos An alias isn't as flexible. for example it can't take arguments. A function is better in most cases. Check [this](http://stackoverflow.com/questions/17568366/how-can-one-create-and-then-use-an-alias-in-a-function-of-a-sourced-bash-script/17568396#17568396) – hek2mgl Aug 09 '13 at 09:33
  • 1
    @fedorqui Didn't know about the `\command` with leading `\ ` approach. I would have just typed the whole path like `/bin/ping`.. Thx for the advice :) – hek2mgl Aug 09 '13 at 09:34
  • @nos I forgot to mention, that aliases will work in interactive shells only. not in shell scripts – hek2mgl Aug 09 '13 at 10:04
  • aliases works in shell scripts if it's defined in the script, but not if it's defined elsewhere, which is how functions behave too. (this will depend on which startup config file is read, you could use other files than .bashrc, e.g. .profile which may, depeinding on your setup be run in non-interactive shells) While less flexible, aliases can take arguments, as `alias ping='ping -w5'` as long as the arguments the alias adds come before any arguments you give when you run it. – nos Aug 09 '13 at 18:52
  • @nos Damn, you are right! beat me because of that `.bashrc` thing. That's lesson 1 but hadn't in mind... However, the fact that an alias can only act as "extended prefixes" what makes it impossible to enforce a parameter and the fact, that I cannot do more than this, let me in most cases decide to use a function – hek2mgl Aug 09 '13 at 19:00