Network.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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\Support;
  12. use Hyperf\Stringable\Str;
  13. use RuntimeException;
  14. class Network
  15. {
  16. public static function ip(): string
  17. {
  18. $ips = [];
  19. if (function_exists('swoole_get_local_ip')) {
  20. $ips = swoole_get_local_ip();
  21. }
  22. if (empty($ips) && function_exists('net_get_interfaces')) {
  23. foreach (net_get_interfaces() ?: [] as $name => $value) {
  24. foreach ($value['unicast'] as $item) {
  25. if (! isset($item['address'])) {
  26. continue;
  27. }
  28. if (! Str::contains($item['address'], ':') && $item['address'] !== '127.0.0.1') {
  29. $ips[$name] = $item['address'];
  30. }
  31. }
  32. }
  33. }
  34. if (is_array($ips) && ! empty($ips)) {
  35. return current($ips);
  36. }
  37. $name = gethostname();
  38. if ($name === false) {
  39. throw new RuntimeException('Can not get the internal IP.');
  40. }
  41. return gethostbyname($name);
  42. }
  43. }