Giter VIP home page Giter VIP logo

ping's Introduction

Ping for PHP Logo

Ping

Build Status

A PHP class to ping hosts.

There are a ton of different methods of pinging a server using PHP, and I've found most to be poorly documented or downright dangerous in their implementation.

Therefore, I've created this simple class, which incorporates the three most popular ping methods (exec() with the system's ping utility, fsockopen(), and socket_create()). Each method has its benefits and drawbacks, and may work better or worse on a particular system.

Installation

$ composer require geerlingguy/ping

Usage

This is a very simple class. Just create an instance, and run ping().

$host = 'www.example.com';
$ping = new \JJG\Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

You can also specify the ttl (maximum hops) and timeout when creating the instance:

$ttl = 128;
$timeout = 5;
$ping = new \JJG\Ping($host, $ttl, $timeout);

...or using the setTtl() or setTimeout() methods:

$ping = new \JJG\Ping($host);
$ping->setTtl(128);
$ping->setTimeout(5);

You can change the host using the setHost() method:

$ping = new \JJG\Ping($host);
...
$ping->setHost('www.anotherexample.com');

License

Ping is licensed under the MIT (Expat) license. See included LICENSE.md.

Author

Ping is maintained by Jeff Geerling, and is used to check servers for Server Check.in, an inexpensive website and server uptime monitoring service.

ping's People

Contributors

adduc avatar divinity76 avatar geerlingguy avatar khandieyea avatar marcbp avatar peec avatar pixelbrackets avatar sergiowww avatar szarka avatar wulfheart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ping's Issues

Support Windows ping in exec()

I've had someone ask about supporting Windows, as the current ping command seems to only work on Mac OS X and Linux servers. I think this is just a matter of setting a flag or autodetecting what kind of system we're on, and going from there...

Possible to fake/mock?

I need to unit test a method that uses this package but I can't figure out how to fake out the request since my CI/CD infrastructure blocks outbound ICMP. Are you able to either A) add the ability to fake the request by adding a static method like Ping::fake(['success' => true]) / Ping::fake(['success' => false]) before the actual Ping::get(), or B) explain how I could use something like Mockery to do this?

Host could not be reached

Hello,

I just installed the library via composer, I copied/pasted the example code given in the readme, but it always returns : Host could not be reached.

image

Did I forget something?

Allow fsockopen for any port

I was looking into using this class, but will be testing against hosts that aren't necessarily webservers, and will need to use the fsockopen method. Could you add a config parameter to specify the port? The default could definitely be 80, but should be overridable.

Support translations

Right now the class uses the hardcoded string 'time=' to find the latency from the exec output, but when the ping program is localized the class incorrectly assumes the host is unreachable.

In dutch for example this should be 'tijd='.

Unable to ping url

OS: Ubuntu 20.04

I'm trying to ping a domain name but every time I ping it, it comes back false however, if I ping an IP address it works fine.

How am I able to ping a domain?

$ping = new Ping('172.217.1.3');
$ping->setTimeout(5);

$latency = $ping->ping();
var_dump($latency);

Returns: 4.27ms

$ping = new Ping('https://google.ca');
$ping->setTimeout(5);

$latency = $ping->ping();
var_dump($latency);

Returns: false

$ping = new Ping('google.ca');
$ping->setTimeout(5);

$latency = $ping->ping();
var_dump($latency);

Returns: false

host not found

I use version 1.x
I use the following code:

$host = "localhost" or "127.0.0.1"
no change result...
$ping = new Ping($host);
        $ping->setTtl(128);
        $ping->setTimeout(5);
        $latency = $ping->ping();
        if ($latency !== false) {
            return $latency; 
        }else{
            return "No Host";
        }

but cannot find the host.

Double socket_close

Show this error:

PHP Warning: socket_close(): 6 is not a valid Socket resource in Ping.php on line 214
PHP Stack trace:
PHP 1. {main}() select_gateway.php:0
PHP 2. JJG\Ping->ping() select_gateway.php:8
PHP 3. socket_close() Ping.php:214

Warning: socket_close(): 6 is not a valid Socket resource in Ping.php on line 214

Remove line 214 in Ping.php solve this problem.

pingExec return false in win8.1

in line 111
$output[1] have string(53) "Respuesta desde 127.0.0.1: bytes=32 tiempo<1m TTL=128"

$response = preg_match("/time(?:=|<)(?[.0-9]+)(?:|\s)ms/", $output[1], $matches);

var_dump($response,$matches);
int(0)
array(0) {
}

ipv6 support

I think ipv6 should be supported in this package, probably switching to using ping6 if host name URL has : what do you think?

$result_line should be set to 3 in Windows XP and Server 2003

By default, $result_line in a Windows system is set to 2. However, in Windows XP and Server 2003 (or maybe other versions), the ping result shows at the 4th line, so $result_line should be set to 3.

ping

I think a better solution is using a loop to remove any empty lines before locate the result line. In this way, $result_line could be set to 1 in both Linux and Windows system.

Uncaught Error: Class 'Ping' not found

Reproducing Error

require 'classes/php/Ping-1.x/JJG/Ping.php';

$ping = new Ping();

Fatal Error: Uncaught Error: Class 'Ping' not found in C:\myfolders\xampp\htdocs...myweb...\

Tried this answer as well, but didn't work as I expected to be
https://stackoverflow.com/a/1179734

Code I've tried:

define('__ROOT__', dirname(dirname(__FILE__)));

spl_autoload_register(function ($class_name) {
	require_once __ROOT__.'/classes/php/Ping-1.x/JJG/'.$class_name.'.php';
	// throw new Exception("Unable to load $class_name.");
});
try {
	$ping = new Ping();
}	catch(Exception $e) {
	echo $e->getMessage();
}

Resulted in the same error.

I'm using XAMPP, my PHP version is 7.2.11.

Undefined output - Exec Command

I'm using this project in a Laravel application with fairly high verbosity of errors, and I receive the following message:

Undefined variable: output in geerlingguy/ping/JJG/Ping.php:234

Instead of letting it assuming the $output variable, can it be defined above?

Please Note: This happened in version 1.1.1

Fix TTL/Timeout Confusion

When originally creating this class, I mistook 'TTL' in ping parlance to mean 'timeout' in seconds on a local computer. Instead, TTL is an indication of how many hops it takes to get from one host to another. Therefore, setting a default value of '5' mean that pings using the exec method would only work in local or small networks (5 hops is not much on the Internet).

Therefore I set the max back to 255, which will work in almost any circumstance. See: http://www.visualware.com/resources/tutorials/tracert.html

Add a way to hide the output of ping

When I pass an invalid domain it return the result of the exec function, any way to hide this?

$ping = new \JJG\Ping('<domain>');
$latency = $ping->ping();
if($latency !== false)
    echo 'Ok';
else {
    echo 'Host could not be reached';
}

And the results:

[root@server ping-sites]# php test_domains.php
ping: unknown host firstdomain.info

Thanks :)

linux-package inetutils-ping causes 'unsupported packet type'

First thank you for this library. It matches perfectly with my needs of an easy to use abstraction of a check via ping. But when I tried to run some tests, the executed ping command failed always. I also tried to run ping directly via console and got the same error message. My setup runs PHP 5.6.25 via docker (php:5.6-fpm).

$ ping -n -c 1 -t 255 -W 10 127.0.0.1
ping: unsupported packet type: 255

The manual output of ping shows, that the error message is correct and that the t-parameter doesn't define TTL. Also the ping API doesn't look like the typical I know.

$ ping --help
Usage: ping [OPTION...] HOST ...
Send ICMP ECHO_REQUEST packets to network hosts.

 Options controlling ICMP request types:
      --address              send ICMP_ADDRESS packets (root only)
      --echo                 send ICMP_ECHO packets (default)
      --mask                 same as --address
      --timestamp            send ICMP_TIMESTAMP packets
  -t, --type=TYPE            send TYPE packets

 Options valid for all request types:

  -c, --count=NUMBER         stop after sending NUMBER packets
  -d, --debug                set the SO_DEBUG option
  -i, --interval=NUMBER      wait NUMBER seconds between sending each packet
  -n, --numeric              do not resolve host addresses
  -r, --ignore-routing       send directly to a host on an attached network
      --ttl=N                specify N as time-to-live
  -T, --tos=NUM              set type of service (TOS) to NUM
  -v, --verbose              verbose output
  -w, --timeout=N            stop after N seconds
  -W, --linger=N             number of seconds to wait for response

 Options valid for --echo requests:

  -f, --flood                flood ping (root only)
      --ip-timestamp=FLAG    IP timestamp of type FLAG, which is one of
                             "tsonly" and "tsaddr"
  -l, --preload=NUMBER       send NUMBER packets as fast as possible before
                             falling into normal mode of behavior (root only)
  -p, --pattern=PATTERN      fill ICMP packet with given pattern (hex)
  -q, --quiet                quiet output
  -R, --route                record route
  -s, --size=NUMBER          send NUMBER data octets

  -?, --help                 give this help list
      --usage                give a short usage message
  -V, --version              print program version

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

Options marked with (root only) are available only to superuser.

Report bugs to <[email protected]>.

The php:5.6-fpm docker-container runs with Debian 8.5 (Jessie) as OS and the ping command is available via inetutils-ping package.

$ dpkg -l | grep ping
ii  inetutils-ping            2:1.9.2.39.3a460-3        amd64        ICMP echo tool

On my host system (Ubuntu 14.04) the ping command runs without a problem. But I noticed, that I have ping from a different package.

$ ping                      
Usage: ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]
            [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]
            [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]
            [-w deadline] [-W timeout] [hop1 ...] destination

I could solve my problem by installing iputils-ping package via apt-get install iputils-ping, which replaced ping.

$ dpkg -l | grep ping
ii  iputils-ping              3:20121221-5+b2           amd64        Tools to test the reachability of network hosts

It would we great, if your library could check, that the executed command runs properly or uses different parameter depending on installed package of ping.

Fix error "Undefined offset: 6 in Ping->ping()"

If a host is unreachable, the latency cannot be determined, because the time=X parameter is not in the result. Therefore, we need to add another check after exploding the result line to see if the $time_param parameter is actually present.

Issues with autoload

I love everything about your application. It was exactly what I was looking for! I integrated it into an internal app I built for my job. I developed it on my laptop running xampp, worked perfectly. I wanted to start using it internally, so I moved it to a ubuntu box. Among other issues that popped up, I haven't been able to get this to work. The error I get is "Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ..." I googled this, and haven't found much in the way of a fix. Any suggestions?

Add unit tests and Travis CI integration

If nothing else, I'd like some very basic functionality tested, since this class seems to be used a little more widely now, and I don't want to break anything with future improvements. I'd also like to sort out the class a little better so it's more flexible and extensible.

why only integer timeout ?

Hi! I need shorter timeout (0.5), but enable to set it, because it is integer in code.
And, what is more dangerous, setting timeout to 0.5 will hang a request (if host is dead).
So please,

  1. could you make it float? for linux
  2. add a note to start page example, about "don't set float timeout, it will be treated as no timeout"
    thanks

escapeshellarg instead of escapeshellcmd

First, I'd like to congrat you for the initiative to make a complete and clean implementation of the 'ping'.

My interest was in the ping using shell command "pingExec()". I see you escaped $host and $ttl using escapeshellcmd, but I think it should be _escapeshellarg_ instead, because the former allows more arguments to be passed to the ping command. You may also use escapeshellcmd around the entire exec_string.

There's a clear explanation of these functions (other than the php doc) at http://stackoverflow.com/a/22739494

pingExec() always returns 0ms under Windows

$time_param appears to be set correctly under the if statement for Windows file systems but the resulting $output array retains the keys after filtering out the empty lines (the very first line being empty is what is actually causing the problem).

Can be fixed by changing line 192 in Ping.php from:

$output = array_filter($output);

to

$output = array_values(array_filter($output));

Ping fails inside cron

I have Ping setup inside of a command-line script that, when run on the command-line, everything works great. I get valid data.

However, when I place the exact same command inside of a crontab, Ping returns with a 'false', however the rest of the script works perfectly, so I know that everything is running fine.

I'm using the exec() style of calling. Is there a better method to get valid data from within a cron job?

Make ping count configurable

Currently, the ping count is hardcoded as 1 ping only. Some users would like to be able to ping maybe 3 times and get an average latency instead, or get further statistics.

Laravel Valet - Host could not be reached

Hi,

I'm trying to use the ping class on my local dev environment with Laravel Valet on macOS.
However I always get the output that the host could not be reached, even when trying to ping google or 1.1.1.1

Ping Fail when below 0

Ping Fails when latency is below 0.5.

Reason:

$latency = round($matches['time']);

When Time is 0.42 ms --> round --> 0 but host is alive!

I removed round() and its working !

[Security] *NO* Root Permissions and Command Executable Permissions Required.

socket_create(AF_INET, SOCK_DGRAM, SOL_SOCKET);

Since Kernel 2.2:

You must set the cap with cap_net_raw+ep to use SOCK_RAW

Since Kernel 2.6.39: Only needs

net.ipv4.ping_group_range = 0 2147483647
ping_group_range - 2 INTEGERS
Restrict ICMP_PROTO datagram sockets to users in the group range. The default is “1 0”, meaning, that nobody (not even root) may create ping sockets. Setting it to “100 100” would grant permissions to the single group. “0 4294967295” would enable it for the world, “100 4294967295” would enable it for the users, but not daemons.

Then you can use ping socket as

socket_create(AF_INET, SOCK_DGRAM, SOL_SOCKET);

Make ping count configurable

Currently, the ping count is hardcoded as 1 ping only. Some users would like to be able to ping maybe 3 times and get an average latency instead, or get further statistics.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.