Completed
Pull Request — master (#20)
by Haralan
18:05 queued 16:21
created

Network   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 9.09%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 4
c 3
b 0
f 2
lcom 0
cbo 1
dl 0
loc 37
ccs 1
cts 11
cp 0.0909
rs 10

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
	public static function is_port_open($host, $port)
22
	{
23
		$connection = @fsockopen($host, $port);
24
		if (is_resource($connection))
25
		{
26
			fclose($connection);
27
			return FALSE;
28
		}
29
		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
	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
			$port = rand($range_start, $range_end);
46
			return Network::is_port_open($host, $port) ? $port : FALSE;
47
		}, $timeout);
48 2
	}
49
}
50