Network.php
1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils;
use RuntimeException;
class Network
{
public static function ip(): string
{
$ips = [];
if (function_exists('swoole_get_local_ip')) {
$ips = swoole_get_local_ip();
}
if (empty($ips) && function_exists('net_get_interfaces')) {
foreach (net_get_interfaces() ?: [] as $name => $value) {
foreach ($value['unicast'] as $item) {
if (! isset($item['address'])) {
continue;
}
if (! Str::contains($item['address'], '::') && $item['address'] !== '127.0.0.1') {
$ips[$name] = $item['address'];
}
}
}
}
if (is_array($ips) && ! empty($ips)) {
return current($ips);
}
/** @var mixed|string $ip */
$ip = gethostbyname(gethostname());
if (is_string($ip)) {
return $ip;
}
throw new RuntimeException('Can not get the internal IP.');
}
}