Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Async DNS resolver for ReactPHP.

License

NotificationsYou must be signed in to change notification settings

reactphp/dns

Repository files navigation

CI statusinstalls on Packagist

Async DNS resolver forReactPHP.

Development version: This branch contains the code for the upcoming v3release. For the code of the current stable v1 release, check out the1.x branch.

The upcoming v3 release will be the way forward for this package. However,we will still actively support v1 for those not yet on the latest version.See alsoinstallation instructions for more details.

The main point of the DNS component is to provide async DNS resolution.However, it is really a toolkit for working with DNS messages, and couldeasily be used to create a DNS server.

Table of contents

Basic usage

The most basic usage is to just create a resolver through the resolverfactory. All you need to give it is a nameserver, then you can start resolvingnames, baby!

$config =React\Dns\Config\Config::loadSystemConfigBlocking();if (!$config->nameservers) {$config->nameservers[] ='8.8.8.8';}$factory =newReact\Dns\Resolver\Factory();$dns =$factory->create($config);$dns->resolve('igor.io')->then(function ($ip) {echo"Host:$ip\n";});

See also thefirst example.

TheConfig class can be used to load the system default config. This is anoperation that may access the filesystem and block. Ideally, this method shouldthus be executed only once before the loop starts and not repeatedly while it isrunning.Note that this class may return anempty configuration if the system configcan not be loaded. As such, you'll likely want to apply a default nameserveras above if none can be found.

Note that the factory loads the hosts file from the filesystem once whencreating the resolver instance.Ideally, this method should thus be executed only once before the loop startsand not repeatedly while it is running.

But there's more.

Caching

You can cache results by configuring the resolver to use aCachedExecutor:

$config =React\Dns\Config\Config::loadSystemConfigBlocking();if (!$config->nameservers) {$config->nameservers[] ='8.8.8.8';}$factory =newReact\Dns\Resolver\Factory();$dns =$factory->createCached($config);$dns->resolve('igor.io')->then(function ($ip) {echo"Host:$ip\n";});...$dns->resolve('igor.io')->then(function ($ip) {echo"Host:$ip\n";});

If the first call returns before the second, only one query will be executed.The second result will be served from an in memory cache.This is particularly useful for long running scripts where the same hostnameshave to be looked up multiple times.

See also thethird example.

Custom cache adapter

By default, the above will use an in memory cache.

You can also specify a custom cache implementingCacheInterface to handle the record cache instead:

$cache =newReact\Cache\ArrayCache();$factory =newReact\Dns\Resolver\Factory();$dns =$factory->createCached('8.8.8.8',null,$cache);

See also the wiki for possiblecache implementations.

ResolverInterface

resolve()

Theresolve(string $domain): PromiseInterface<string> method can be used toresolve the given $domain name to a single IPv4 address (typeA query).

$resolver->resolve('reactphp.org')->then(function ($ip) {echo'IP for reactphp.org is' .$ip .PHP_EOL;});

This is one of the main methods in this package. It sends a DNS queryfor the given $domain name to your DNS server and returns a single IPaddress on success.

If the DNS server sends a DNS response message that contains more thanone IP address for this query, it will randomly pick one of the IPaddresses from the response. If you want the full list of IP addressesor want to send a different type of query, you should use theresolveAll() method instead.

If the DNS server sends a DNS response message that indicates an errorcode, this method will reject with aRecordNotFoundException. Itsmessage and code can be used to check for the response code.

If the DNS communication fails and the server does not respond with avalid response message, this message will reject with anException.

Pending DNS queries can be cancelled by cancelling its pending promise like so:

$promise =$resolver->resolve('reactphp.org');$promise->cancel();

resolveAll()

TheresolveAll(string $host, int $type): PromiseInterface<array> method can be used toresolve all record values for the given $domain name and query $type.

$resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) {echo'IPv4 addresses for reactphp.org' .implode(',',$ips) .PHP_EOL;});$resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) {echo'IPv6 addresses for reactphp.org' .implode(',',$ips) .PHP_EOL;});

This is one of the main methods in this package. It sends a DNS queryfor the given $domain name to your DNS server and returns a list with allrecord values on success.

If the DNS server sends a DNS response message that contains one or morerecords for this query, it will return a list with all record valuesfrom the response. You can use theMessage::TYPE_* constants to controlwhich type of query will be sent. Note that this method always returns alist of record values, but each record value type depends on the querytype. For example, it returns the IPv4 addresses for typeA queries,the IPv6 addresses for typeAAAA queries, the hostname for typeNS,CNAME andPTR queries and structured data for other queries. See alsotheRecord documentation for more details.

If the DNS server sends a DNS response message that indicates an errorcode, this method will reject with aRecordNotFoundException. Itsmessage and code can be used to check for the response code.

If the DNS communication fails and the server does not respond with avalid response message, this message will reject with anException.

Pending DNS queries can be cancelled by cancelling its pending promise like so:

$promise =$resolver->resolveAll('reactphp.org', Message::TYPE_AAAA);$promise->cancel();

Advanced Usage

UdpTransportExecutor

TheUdpTransportExecutor can be used tosend DNS queries over a UDP transport.

This is the main class that sends a DNS query to your DNS server and is usedinternally by theResolver for the actual message transport.

For more advanced usages one can utilize this class directly.The following example looks up theIPv6 address forigor.io.

$executor =newUdpTransportExecutor('8.8.8.8:53');$executor->query(newQuery($name, Message::TYPE_AAAA, Message::CLASS_IN))->then(function (Message$message) {foreach ($message->answersas$answer) {echo'IPv6:' .$answer->data .PHP_EOL;    }},'printf');

See also thefourth example.

Note that this executor does not implement a timeout, so you will very likelywant to use this in combination with aTimeoutExecutor like this:

$executor =newTimeoutExecutor(newUdpTransportExecutor($nameserver),3.0);

Also note that this executor uses an unreliable UDP transport and that itdoes not implement any retry logic, so you will likely want to use this incombination with aRetryExecutor like this:

$executor =newRetryExecutor(newTimeoutExecutor(newUdpTransportExecutor($nameserver),3.0    ));

Note that this executor is entirely async and as such allows you to executeany number of queries concurrently. You should probably limit the number ofconcurrent queries in your application or you're very likely going to facerate limitations and bans on the resolver end. For many common applications,you may want to avoid sending the same query multiple times when the firstone is still pending, so you will likely want to use this in combination withaCoopExecutor like this:

$executor =newCoopExecutor(newRetryExecutor(newTimeoutExecutor(newUdpTransportExecutor($nameserver),3.0        )    ));

Internally, this class uses PHP's UDP sockets and does not take advantageofreact/datagram purely fororganizational reasons to avoid a cyclic dependency between the twopackages. Higher-level components should take advantage of the Datagramcomponent instead of reimplementing this socket logic from scratch.

TcpTransportExecutor

TheTcpTransportExecutor class can be used tosend DNS queries over a TCP/IP stream transport.

This is one of the main classes that send a DNS query to your DNS server.

For more advanced usages one can utilize this class directly.The following example looks up theIPv6 address forreactphp.org.

$executor =newTcpTransportExecutor('8.8.8.8:53');$executor->query(newQuery($name, Message::TYPE_AAAA, Message::CLASS_IN))->then(function (Message$message) {foreach ($message->answersas$answer) {echo'IPv6:' .$answer->data .PHP_EOL;    }},'printf');

See alsoexample #92.

Note that this executor does not implement a timeout, so you will very likelywant to use this in combination with aTimeoutExecutor like this:

$executor =newTimeoutExecutor(newTcpTransportExecutor($nameserver),3.0);

Unlike theUdpTransportExecutor, this class uses a reliable TCP/IPtransport, so you do not necessarily have to implement any retry logic.

Note that this executor is entirely async and as such allows you to executequeries concurrently. The first query will establish a TCP/IP socketconnection to the DNS server which will be kept open for a short period.Additional queries will automatically reuse this existing socket connectionto the DNS server, will pipeline multiple requests over this singleconnection and will keep an idle connection open for a short period. Theinitial TCP/IP connection overhead may incur a slight delay if you only sendoccasional queries – when sending a larger number of concurrent queries overan existing connection, it becomes increasingly more efficient and avoidscreating many concurrent sockets like the UDP-based executor. You may stillwant to limit the number of (concurrent) queries in your application or youmay be facing rate limitations and bans on the resolver end. For many commonapplications, you may want to avoid sending the same query multiple timeswhen the first one is still pending, so you will likely want to use this incombination with aCoopExecutor like this:

$executor =newCoopExecutor(newTimeoutExecutor(newTcpTransportExecutor($nameserver),3.0    ));

Internally, this class uses PHP's TCP/IP sockets and does not take advantageofreact/socket purely fororganizational reasons to avoid a cyclic dependency between the twopackages. Higher-level components should take advantage of the Socketcomponent instead of reimplementing this socket logic from scratch.

SelectiveTransportExecutor

TheSelectiveTransportExecutor class can be used toSend DNS queries over a UDP or TCP/IP stream transport.

This class will automatically choose the correct transport protocol to senda DNS query to your DNS server. It will always try to send it over the moreefficient UDP transport first. If this query yields a size related issue(truncated messages), it will retry over a streaming TCP/IP transport.

For more advanced usages one can utilize this class directly.The following example looks up theIPv6 address forreactphp.org.

$executor =newSelectiveTransportExecutor($udpExecutor,$tcpExecutor);$executor->query(newQuery($name, Message::TYPE_AAAA, Message::CLASS_IN))->then(function (Message$message) {foreach ($message->answersas$answer) {echo'IPv6:' .$answer->data .PHP_EOL;    }},'printf');

Note that this executor only implements the logic to select the correcttransport for the given DNS query. Implementing the correct transport logic,implementing timeouts and any retry logic is left up to the given executors,see alsoUdpTransportExecutor andTcpTransportExecutor for more details.

Note that this executor is entirely async and as such allows you to executeany number of queries concurrently. You should probably limit the number ofconcurrent queries in your application or you're very likely going to facerate limitations and bans on the resolver end. For many common applications,you may want to avoid sending the same query multiple times when the firstone is still pending, so you will likely want to use this in combination withaCoopExecutor like this:

$executor =newCoopExecutor(newSelectiveTransportExecutor($datagramExecutor,$streamExecutor    ));

HostsFileExecutor

Note that the aboveUdpTransportExecutor class always performs an actual DNS query.If you also want to take entries from your hosts file into account, you mayuse this code:

$hosts = \React\Dns\Config\HostsFile::loadFromPathBlocking();$executor =newUdpTransportExecutor('8.8.8.8:53');$executor =newHostsFileExecutor($hosts,$executor);$executor->query(newQuery('localhost', Message::TYPE_A, Message::CLASS_IN));

Install

The recommended way to install this library isthrough Composer.New to Composer?

Once released, this project will followSemVer.At the moment, this will install the latest development version:

composer require react/dns:^3@dev

See also theCHANGELOG for details about version upgrades.

This project aims to run on any platform and thus does not require any PHPextensions and supports running on PHP 7.1 through current PHP 8+.It'shighly recommended to use the latest supported PHP version for this project.

Tests

To run the test suite, you first need to clone this repo and then install alldependenciesthrough Composer:

composer install

To run the test suite, go to the project root and run:

vendor/bin/phpunit

The test suite also contains a number of functional integration tests that relyon a stable internet connection.If you do not want to run these, they can simply be skipped like this:

vendor/bin/phpunit --exclude-group internet

License

MIT, seeLICENSE file.

References

  • RFC 1034 Domain Names - Concepts and Facilities
  • RFC 1035 Domain Names - Implementation and Specification

About

Async DNS resolver for ReactPHP.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •  
  •  
  •  

Contributors17

Languages


[8]ページ先頭

©2009-2025 Movatter.jp