Skip to content

Instantly share code, notes, and snippets.

@patelnwd
Last active July 26, 2025 12:21
Show Gist options
  • Select an option

  • Save patelnwd/e065e56a8dbc30c595be017c375fce8a to your computer and use it in GitHub Desktop.

Select an option

Save patelnwd/e065e56a8dbc30c595be017c375fce8a to your computer and use it in GitHub Desktop.
This utility class provides methods to test network connectivity to remote hosts using a specified port and timeout. It can be used for service availability checks, network diagnostics, and ensuring dependent services are accessible.
<?php
declare(strict_types=1);
namespace App\Library\Utility;
use Cake\Http\Exception\NotFoundException;
/**
* NetworkConnection class for testing connectivity to remote hosts
*
* This utility class provides methods to test network connectivity to remote hosts
* using a specified port and timeout. It can be used for service availability checks,
* network diagnostics, and ensuring dependent services are accessible.
*
* Features:
* - Connection testing with customizable timeout
* - Response time measurement in milliseconds
* - Error handling with detailed error information
* - Chainable interface for flexible usage
* - Static convenience methods for quick tests
*
* @author Mukesh Kumar <[email protected]>
* @version 1.0.0
* @since 2023-01-01
*/
class NetworkConnection
{
private string $host;
private int $port;
private float $timeout;
private string $lastError;
private int $lastErrorNo;
private float $responseTime;
private bool $isConnected;
/**
* Constructor
*
* @param string $host The hostname or IP address to connect to
* @param int $port The port number to test
* @param float $timeout Connection timeout in seconds
*/
public function __construct(string $host, int $port, float $timeout = 3.0)
{
$this->host = $this->setHost($host)->getHost();
$this->port = $port;
$this->timeout = $timeout;
$this->lastError = '';
$this->lastErrorNo = 0;
$this->responseTime = 0.0;
$this->isConnected = false;
}
/**
* Set the target host
*
* @param string $host The hostname or IP address
*
* @return self For method chaining
*/
public function setHost(string $host): self
{
$this->host = parse_url($host, PHP_URL_HOST);
return $this;
}
/**
* Get the current host
*
* @return string The current host
*/
public function getHost(): string
{
return $this->host;
}
/**
* Set the target port
*
* @param int $port The port number
*
* @return self For method chaining
*/
public function setPort(int $port): self
{
$this->port = $port;
return $this;
}
/**
* Get the current port
*
* @return int The current port
*/
public function getPort(): int
{
return $this->port;
}
/**
* Set connection timeout
*
* @param float $timeout Timeout in seconds
*
* @return self For method chaining
*/
public function setTimeout(float $timeout): self
{
$this->timeout = $timeout;
return $this;
}
/**
* Get the current timeout
*
* @return float The current timeout in seconds
*/
public function getTimeout(): float
{
return $this->timeout;
}
/**
* Test the connection
*
* @return self For method chaining
*/
public function test(): self
{
$startTime = microtime(true);
$fp = @fsockopen($this->host, $this->port, $errorNo, $errorStr, $this->timeout);
$endTime = microtime(true);
$this->responseTime = round(($endTime - $startTime) * 1000, 2); // in milliseconds
if (!$fp) {
$this->isConnected = false;
$this->lastError = $errorStr;
$this->lastErrorNo = $errorNo;
} else {
$this->isConnected = true;
$this->lastError = '';
$this->lastErrorNo = 0;
fclose($fp);
}
return $this;
}
/**
* Get the response time of the last test
*
* @return float Response time in milliseconds
*/
public function getResponseTime(): float
{
return $this->responseTime;
}
/**
* Get the last error message
*
* @return string Error message
*/
public function getLastError(): string
{
return $this->lastError;
}
/**
* Get the last error number
*
* @return int Error number
*/
public function getLastErrorNo(): int
{
return $this->lastErrorNo;
}
/**
* Check if the last connection attempt was successful
*
* @return bool Connection status
*/
public function isConnected(): bool
{
return $this->isConnected;
}
/**
* Get a formatted result of the connection test
*
* @return string Formatted result
*/
public function getFormattedResult(): string
{
$result = "Connection test to {$this->host} on port {$this->port}:\n";
if ($this->isConnected) {
$result .= "Status: Connected\n";
$result .= "Response time: {$this->responseTime} ms\n";
} else {
$result .= "Status: Failed\n";
$result .= "Error: {$this->lastError} (Code: {$this->lastErrorNo})\n";
if ($this->responseTime > 0) {
$result .= "Time before failure: {$this->responseTime} ms\n";
}
}
return $result;
}
/**
* Shorthand method to create instance and test in one call
*
* @param string $host The hostname or IP address
* @param int $port The port number
* @param float $timeout Connection timeout in seconds
*
* @return self Instance with test results
*/
public static function quickTest(string $host, int $port, float $timeout = 3.0): self
{
return (new self($host, $port, $timeout))->test();
}
/**
* Connect to the host and port or throw an exception
*
* @param string $host The hostname or IP address
* @param int $port The port number
* @param float $timeout Connection timeout in seconds
*
* @return bool Response time in milliseconds
*/
public static function connectOrFail(string $host, int $port, float $timeout = 3.0): bool
{
$connection = new self($host, $port, $timeout);
$connection->test();
if (!$connection->isConnected()) {
throw new NotFoundException(
sprintf(
'Failed to connect to %s on port %d: %s (Error code: %d)',
$host,
$port,
$connection->getLastError(),
$connection->getLastErrorNo()
)
);
}
return $connection->isConnected();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment