Swoole Coroutine System: gethostbyname

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Coroutine\System::gethostbyname(string $domain, int $family = AF_INET, float $timeout = -1): string|false

Parameters

host

Hostname to lookup and resolve to an IP. For example: OpenSwoole.co.uk

family

The domain family to use, AF_INET represents IPv4 addresses and AF_INET6 represents IPv6 addresses.

timeout

A float in seconds for how long before timing out the lookup. Because a float is used, 1.5 means 1.5 seconds. By default -1 means don't time out. The lowest possible value is 0.001.

Return

If successful it returns the IP address of the hostname as a string and false when there was an error. Use OpenSwoole\Util::getLastErrorCode() to see what went wrong.

Description

Get the IP address of a hostname. Resolves the domain name to an IP, this method won't block other processes, must be used within a coroutine.

You can also use OpenSwoole\Coroutine\System::dnsLookup to get IP of a hostname.


Example

<?php

co::set(['dns_server' => '192.0.0.1:53']);

co::run(function()
{
    $ip = OpenSwoole\Coroutine\System::gethostbyname('openswoole.com');
    var_dump($ip);
});

Output:

<?php

string(14) "172.67.221.150"

If using a timeout and the hostname cannot be resolved within the specified time then, the function will return:

<?php

co::run(function()
{
    $ip = OpenSwoole\Coroutine\System::gethostbyname('openswoole.com', AF_INET, 3);
    var_dump($ip);
});
Last updated on September 21, 2022