Swoole Coroutine System: gethostbyname

Declaration

<?php
Swoole\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: swoole.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 swoole_last_error() 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 Swoole\Coroutine\System::dnsLookup to get IP of a hostname.


Example

<?php

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

Co\run(function()
{
    $ip = Swoole\Coroutine\System::gethostbyname('www.swoole.co.uk');
    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 = Swoole\Coroutine\System::gethostbyname('www.swoole.co.uk', AF_INET, 3);
    var_dump($ip);
});