Network   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 37
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A is_port_open() 0 10 2
A ephimeral_port() 0 7 2
1
<?php
2
3
namespace Openbuildings\Spiderling;
4
5
/**
6
 * Network helper for deailng with ports
7
 *
8
 * @package    Openbuildings\Spiderling
9
 * @author     Ivan Kerin
10
 * @copyright  (c) 2013 OpenBuildings Ltd.
11
 * @license    http://spdx.org/licenses/BSD-3-Clause
12
 */
13
class Network {
14
15
	/**
16
	 * Check if a port is open
17
	 * @param  string  $host
18
	 * @param  integer  $port
19
	 * @return boolean
20
	 */
21 3
	public static function is_port_open($host, $port)
22
	{
23 3
		$connection = @fsockopen($host, $port);
24 3
		if (is_resource($connection))
25
		{
26 3
			fclose($connection);
27 3
			return FALSE;
28
		}
29 3
		return TRUE;
30
	}
31
32
	/**
33
	 * Find an open port in a given range, trying several times.
34
	 * Return FALSE if no open port is found after a timeout (1 second by default)
35
	 *
36
	 * @param  string  $host
37
	 * @param  integer $range_start
38
	 * @param  integer $range_end
39
	 * @param  integer $timeout
40
	 * @return integer|boolean
41
	 */
42 2
	public static function ephimeral_port($host, $range_start = 1000, $range_end = 5000, $timeout = 1000)
43
	{
44
		return Attempt::make(function() use ($host, $range_start, $range_end) {
45 2
			$port = rand($range_start, $range_end);
46 2
			return Network::is_port_open($host, $port) ? $port : FALSE;
47 2
		}, $timeout);
48
	}
49
}
50