setName('ping') ->setDescription('Ping to host and return SLA metrics') ->setHelp('Se requieren parĂ¡metros para poder realizar la correcta consulta.') ->setDefinition(array( new InputArgument('ip', InputArgument::OPTIONAL,"IP"), new InputOption('timeout', null, InputOption::VALUE_NONE,"Timeout", null), new InputOption('interval', null, InputOption::VALUE_NONE,"Interval", null), new InputOption('count', null, InputOption::VALUE_NONE,"Count", null) )) ; } /** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $ip = $input->getArgument('ip'); if(!$ip) return $output->writeln(json_encode(array('message' => 'IP is required'))); $timeout = $input->getOption('timeout'); $interval = $input->getOption('interval'); $count = $input->getOption('count'); $data = $this->ping($ip, $timeout, $interval, $count); if(!is_array($data)) { $data = array(); } $output->writeln(json_encode($data)); } function ping($ip, $timeout = 1, $int = 0.5, $i = 5) { if(! $timeout ) $timeout = 1; if(! $int ) $int = 0.5; if(! $i ) $i = 5; /* ICMP ping packet with a pre-calculated checksum */ $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; $result = array(); $socket = socket_create(AF_INET, SOCK_RAW, 1); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0)); socket_connect($socket, $ip, null); $n = $c = $total = 0; $jitter = array(); $last = null; for($a = 1; $a <= $i; $a++) { $ts = microtime(true); socket_send($socket, $package, strLen($package), 0); if (socket_read($socket, 255)) { $r = ((microtime(true) - $ts) / 2) * 1000; if(is_null($last)) { $last = $r; } else { $jitter[] = abs(($last - $r)); } $total += $r; $result[] = $r; $c++; } else { $result[] = false; $n++; } if ($int< 1) {usleep($int * 1000000);}else{sleep($int);} } socket_close($socket); $data = array(); if($c > 0) { $data['latency'] = round(($total) / $c,2); } if($jitter) { $data['jitter'] = round(array_sum($jitter) / count($jitter),2); } if($i > 0) { $data['loss'] = round(($n / $i) * 100,2); } return $data; } }