Network.php 1.3 KB

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