{"id":18941221,"url":"https://github.com/reactphp/dns","last_synced_at":"2025-04-13T16:10:35.702Z","repository":{"id":4605809,"uuid":"5749054","full_name":"reactphp/dns","owner":"reactphp","description":"Async DNS resolver for ReactPHP.","archived":false,"fork":false,"pushed_at":"2025-03-12T07:50:57.000Z","size":582,"stargazers_count":515,"open_issues_count":14,"forks_count":59,"subscribers_count":21,"default_branch":"3.x","last_synced_at":"2025-04-10T00:18:26.332Z","etag":null,"topics":["dns","php","reactphp"],"latest_commit_sha":null,"homepage":"https://reactphp.org/dns/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reactphp.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null},"funding":{"github":["reactphp","clue","WyriHaximus"],"open_collective":"reactphp"}},"created_at":"2012-09-10T12:21:27.000Z","updated_at":"2025-04-01T06:29:05.000Z","dependencies_parsed_at":"2023-07-05T20:16:40.616Z","dependency_job_id":"07a5bf90-5d04-475f-a032-e04748330391","html_url":"https://github.com/reactphp/dns","commit_stats":{"total_commits":317,"total_committers":19,"mean_commits":16.68421052631579,"dds":0.5583596214511042,"last_synced_commit":"c134600642fa615b46b41237ef243daa65bb64ec"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reactphp%2Fdns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reactphp%2Fdns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reactphp%2Fdns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reactphp%2Fdns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reactphp","download_url":"https://codeload.github.com/reactphp/dns/tar.gz/refs/heads/3.x","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248676992,"owners_count":21144034,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dns","php","reactphp"],"created_at":"2024-11-08T12:26:45.722Z","updated_at":"2025-04-13T16:10:35.658Z","avatar_url":"https://github.com/reactphp.png","language":"PHP","funding_links":["https://github.com/sponsors/reactphp","https://github.com/sponsors/clue","https://github.com/sponsors/WyriHaximus","https://opencollective.com/reactphp"],"categories":[],"sub_categories":[],"readme":"# DNS\n\n[![CI status](https://github.com/reactphp/dns/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/dns/actions)\n[![installs on Packagist](https://img.shields.io/packagist/dt/react/dns?color=blue\u0026label=installs%20on%20Packagist)](https://packagist.org/packages/react/dns)\n\nAsync DNS resolver for [ReactPHP](https://reactphp.org/).\n\n\u003e **Development version:** This branch contains the code for the upcoming v3\n\u003e release. For the code of the current stable v1 release, check out the\n\u003e [`1.x` branch](https://github.com/reactphp/dns/tree/1.x).\n\u003e\n\u003e The upcoming v3 release will be the way forward for this package. However,\n\u003e we will still actively support v1 for those not yet on the latest version.\n\u003e See also [installation instructions](#install) for more details.\n\nThe main point of the DNS component is to provide async DNS resolution.\nHowever, it is really a toolkit for working with DNS messages, and could\neasily be used to create a DNS server.\n\n**Table of contents**\n\n* [Basic usage](#basic-usage)\n* [Caching](#caching)\n  * [Custom cache adapter](#custom-cache-adapter)\n* [ResolverInterface](#resolverinterface)\n  * [resolve()](#resolve)\n  * [resolveAll()](#resolveall)\n* [Advanced usage](#advanced-usage)\n  * [UdpTransportExecutor](#udptransportexecutor)\n  * [TcpTransportExecutor](#tcptransportexecutor)\n  * [SelectiveTransportExecutor](#selectivetransportexecutor)\n  * [HostsFileExecutor](#hostsfileexecutor)\n* [Install](#install)\n* [Tests](#tests)\n* [License](#license)\n* [References](#references)\n\n## Basic usage\n\nThe most basic usage is to just create a resolver through the resolver\nfactory. All you need to give it is a nameserver, then you can start resolving\nnames, baby!\n\n```php\n$config = React\\Dns\\Config\\Config::loadSystemConfigBlocking();\nif (!$config-\u003enameservers) {\n    $config-\u003enameservers[] = '8.8.8.8';\n}\n\n$factory = new React\\Dns\\Resolver\\Factory();\n$dns = $factory-\u003ecreate($config);\n\n$dns-\u003eresolve('igor.io')-\u003ethen(function ($ip) {\n    echo \"Host: $ip\\n\";\n});\n```\n\nSee also the [first example](examples).\n\nThe `Config` class can be used to load the system default config. This is an\noperation that may access the filesystem and block. Ideally, this method should\nthus be executed only once before the loop starts and not repeatedly while it is\nrunning.\nNote that this class may return an *empty* configuration if the system config\ncan not be loaded. As such, you'll likely want to apply a default nameserver\nas above if none can be found.\n\n\u003e Note that the factory loads the hosts file from the filesystem once when\n  creating the resolver instance.\n  Ideally, this method should thus be executed only once before the loop starts\n  and not repeatedly while it is running.\n\nBut there's more.\n\n## Caching\n\nYou can cache results by configuring the resolver to use a `CachedExecutor`:\n\n```php\n$config = React\\Dns\\Config\\Config::loadSystemConfigBlocking();\nif (!$config-\u003enameservers) {\n    $config-\u003enameservers[] = '8.8.8.8';\n}\n\n$factory = new React\\Dns\\Resolver\\Factory();\n$dns = $factory-\u003ecreateCached($config);\n\n$dns-\u003eresolve('igor.io')-\u003ethen(function ($ip) {\n    echo \"Host: $ip\\n\";\n});\n\n...\n\n$dns-\u003eresolve('igor.io')-\u003ethen(function ($ip) {\n    echo \"Host: $ip\\n\";\n});\n```\n\nIf the first call returns before the second, only one query will be executed.\nThe second result will be served from an in memory cache.\nThis is particularly useful for long running scripts where the same hostnames\nhave to be looked up multiple times.\n\nSee also the [third example](examples).\n\n### Custom cache adapter\n\nBy default, the above will use an in memory cache.\n\nYou can also specify a custom cache implementing [`CacheInterface`](https://github.com/reactphp/cache) to handle the record cache instead:\n\n```php\n$cache = new React\\Cache\\ArrayCache();\n$factory = new React\\Dns\\Resolver\\Factory();\n$dns = $factory-\u003ecreateCached('8.8.8.8', null, $cache);\n```\n\nSee also the wiki for possible [cache implementations](https://github.com/reactphp/react/wiki/Users#cache-implementations).\n\n## ResolverInterface\n\n\u003ca id=\"resolver\"\u003e\u003c!-- legacy reference --\u003e\u003c/a\u003e\n\n### resolve()\n\nThe `resolve(string $domain): PromiseInterface\u003cstring\u003e` method can be used to\nresolve the given $domain name to a single IPv4 address (type `A` query).\n\n```php\n$resolver-\u003eresolve('reactphp.org')-\u003ethen(function ($ip) {\n    echo 'IP for reactphp.org is ' . $ip . PHP_EOL;\n});\n```\n\nThis is one of the main methods in this package. It sends a DNS query\nfor the given $domain name to your DNS server and returns a single IP\naddress on success.\n\nIf the DNS server sends a DNS response message that contains more than\none IP address for this query, it will randomly pick one of the IP\naddresses from the response. If you want the full list of IP addresses\nor want to send a different type of query, you should use the\n[`resolveAll()`](#resolveall) method instead.\n\nIf the DNS server sends a DNS response message that indicates an error\ncode, this method will reject with a `RecordNotFoundException`. Its\nmessage and code can be used to check for the response code.\n\nIf the DNS communication fails and the server does not respond with a\nvalid response message, this message will reject with an `Exception`.\n\nPending DNS queries can be cancelled by cancelling its pending promise like so:\n\n```php\n$promise = $resolver-\u003eresolve('reactphp.org');\n\n$promise-\u003ecancel();\n```\n\n### resolveAll()\n\nThe `resolveAll(string $host, int $type): PromiseInterface\u003carray\u003e` method can be used to\nresolve all record values for the given $domain name and query $type.\n\n```php\n$resolver-\u003eresolveAll('reactphp.org', Message::TYPE_A)-\u003ethen(function ($ips) {\n    echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL;\n});\n\n$resolver-\u003eresolveAll('reactphp.org', Message::TYPE_AAAA)-\u003ethen(function ($ips) {\n    echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL;\n});\n```\n\nThis is one of the main methods in this package. It sends a DNS query\nfor the given $domain name to your DNS server and returns a list with all\nrecord values on success.\n\nIf the DNS server sends a DNS response message that contains one or more\nrecords for this query, it will return a list with all record values\nfrom the response. You can use the `Message::TYPE_*` constants to control\nwhich type of query will be sent. Note that this method always returns a\nlist of record values, but each record value type depends on the query\ntype. For example, it returns the IPv4 addresses for type `A` queries,\nthe IPv6 addresses for type `AAAA` queries, the hostname for type `NS`,\n`CNAME` and `PTR` queries and structured data for other queries. See also\nthe `Record` documentation for more details.\n\nIf the DNS server sends a DNS response message that indicates an error\ncode, this method will reject with a `RecordNotFoundException`. Its\nmessage and code can be used to check for the response code.\n\nIf the DNS communication fails and the server does not respond with a\nvalid response message, this message will reject with an `Exception`.\n\nPending DNS queries can be cancelled by cancelling its pending promise like so:\n\n```php\n$promise = $resolver-\u003eresolveAll('reactphp.org', Message::TYPE_AAAA);\n\n$promise-\u003ecancel();\n```\n\n## Advanced Usage\n\n### UdpTransportExecutor\n\nThe `UdpTransportExecutor` can be used to\nsend DNS queries over a UDP transport.\n\nThis is the main class that sends a DNS query to your DNS server and is used\ninternally by the `Resolver` for the actual message transport.\n\nFor more advanced usages one can utilize this class directly.\nThe following example looks up the `IPv6` address for `igor.io`.\n\n```php\n$executor = new UdpTransportExecutor('8.8.8.8:53');\n\n$executor-\u003equery(\n    new Query($name, Message::TYPE_AAAA, Message::CLASS_IN)\n)-\u003ethen(function (Message $message) {\n    foreach ($message-\u003eanswers as $answer) {\n        echo 'IPv6: ' . $answer-\u003edata . PHP_EOL;\n    }\n}, 'printf');\n```\n\nSee also the [fourth example](examples).\n\nNote that this executor does not implement a timeout, so you will very likely\nwant to use this in combination with a `TimeoutExecutor` like this:\n\n```php\n$executor = new TimeoutExecutor(\n    new UdpTransportExecutor($nameserver),\n    3.0\n);\n```\n\nAlso note that this executor uses an unreliable UDP transport and that it\ndoes not implement any retry logic, so you will likely want to use this in\ncombination with a `RetryExecutor` like this:\n\n```php\n$executor = new RetryExecutor(\n    new TimeoutExecutor(\n        new UdpTransportExecutor($nameserver),\n        3.0\n    )\n);\n```\n\nNote that this executor is entirely async and as such allows you to execute\nany number of queries concurrently. You should probably limit the number of\nconcurrent queries in your application or you're very likely going to face\nrate limitations and bans on the resolver end. For many common applications,\nyou may want to avoid sending the same query multiple times when the first\none is still pending, so you will likely want to use this in combination with\na `CoopExecutor` like this:\n\n```php\n$executor = new CoopExecutor(\n    new RetryExecutor(\n        new TimeoutExecutor(\n            new UdpTransportExecutor($nameserver),\n            3.0\n        )\n    )\n);\n```\n\n\u003e Internally, this class uses PHP's UDP sockets and does not take advantage\n  of [react/datagram](https://github.com/reactphp/datagram) purely for\n  organizational reasons to avoid a cyclic dependency between the two\n  packages. Higher-level components should take advantage of the Datagram\n  component instead of reimplementing this socket logic from scratch.\n\n### TcpTransportExecutor\n\nThe `TcpTransportExecutor` class can be used to\nsend DNS queries over a TCP/IP stream transport.\n\nThis is one of the main classes that send a DNS query to your DNS server.\n\nFor more advanced usages one can utilize this class directly.\nThe following example looks up the `IPv6` address for `reactphp.org`.\n\n```php\n$executor = new TcpTransportExecutor('8.8.8.8:53');\n\n$executor-\u003equery(\n    new Query($name, Message::TYPE_AAAA, Message::CLASS_IN)\n)-\u003ethen(function (Message $message) {\n    foreach ($message-\u003eanswers as $answer) {\n        echo 'IPv6: ' . $answer-\u003edata . PHP_EOL;\n    }\n}, 'printf');\n```\n\nSee also [example #92](examples).\n\nNote that this executor does not implement a timeout, so you will very likely\nwant to use this in combination with a `TimeoutExecutor` like this:\n\n```php\n$executor = new TimeoutExecutor(\n    new TcpTransportExecutor($nameserver),\n    3.0\n);\n```\n\nUnlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP\ntransport, so you do not necessarily have to implement any retry logic.\n\nNote that this executor is entirely async and as such allows you to execute\nqueries concurrently. The first query will establish a TCP/IP socket\nconnection to the DNS server which will be kept open for a short period.\nAdditional queries will automatically reuse this existing socket connection\nto the DNS server, will pipeline multiple requests over this single\nconnection and will keep an idle connection open for a short period. The\ninitial TCP/IP connection overhead may incur a slight delay if you only send\noccasional queries – when sending a larger number of concurrent queries over\nan existing connection, it becomes increasingly more efficient and avoids\ncreating many concurrent sockets like the UDP-based executor. You may still\nwant to limit the number of (concurrent) queries in your application or you\nmay be facing rate limitations and bans on the resolver end. For many common\napplications, you may want to avoid sending the same query multiple times\nwhen the first one is still pending, so you will likely want to use this in\ncombination with a `CoopExecutor` like this:\n\n```php\n$executor = new CoopExecutor(\n    new TimeoutExecutor(\n        new TcpTransportExecutor($nameserver),\n        3.0\n    )\n);\n```\n\n\u003e Internally, this class uses PHP's TCP/IP sockets and does not take advantage\n  of [react/socket](https://github.com/reactphp/socket) purely for\n  organizational reasons to avoid a cyclic dependency between the two\n  packages. Higher-level components should take advantage of the Socket\n  component instead of reimplementing this socket logic from scratch.\n\n### SelectiveTransportExecutor\n\nThe `SelectiveTransportExecutor` class can be used to\nSend DNS queries over a UDP or TCP/IP stream transport.\n\nThis class will automatically choose the correct transport protocol to send\na DNS query to your DNS server. It will always try to send it over the more\nefficient UDP transport first. If this query yields a size related issue\n(truncated messages), it will retry over a streaming TCP/IP transport.\n\nFor more advanced usages one can utilize this class directly.\nThe following example looks up the `IPv6` address for `reactphp.org`.\n\n```php\n$executor = new SelectiveTransportExecutor($udpExecutor, $tcpExecutor);\n\n$executor-\u003equery(\n    new Query($name, Message::TYPE_AAAA, Message::CLASS_IN)\n)-\u003ethen(function (Message $message) {\n    foreach ($message-\u003eanswers as $answer) {\n        echo 'IPv6: ' . $answer-\u003edata . PHP_EOL;\n    }\n}, 'printf');\n```\n\nNote that this executor only implements the logic to select the correct\ntransport for the given DNS query. Implementing the correct transport logic,\nimplementing timeouts and any retry logic is left up to the given executors,\nsee also [`UdpTransportExecutor`](#udptransportexecutor) and\n[`TcpTransportExecutor`](#tcptransportexecutor) for more details.\n\nNote that this executor is entirely async and as such allows you to execute\nany number of queries concurrently. You should probably limit the number of\nconcurrent queries in your application or you're very likely going to face\nrate limitations and bans on the resolver end. For many common applications,\nyou may want to avoid sending the same query multiple times when the first\none is still pending, so you will likely want to use this in combination with\na `CoopExecutor` like this:\n\n```php\n$executor = new CoopExecutor(\n    new SelectiveTransportExecutor(\n        $datagramExecutor,\n        $streamExecutor\n    )\n);\n```\n\n### HostsFileExecutor\n\nNote that the above `UdpTransportExecutor` class always performs an actual DNS query.\nIf you also want to take entries from your hosts file into account, you may\nuse this code:\n\n```php\n$hosts = \\React\\Dns\\Config\\HostsFile::loadFromPathBlocking();\n\n$executor = new UdpTransportExecutor('8.8.8.8:53');\n$executor = new HostsFileExecutor($hosts, $executor);\n\n$executor-\u003equery(\n    new Query('localhost', Message::TYPE_A, Message::CLASS_IN)\n);\n```\n\n## Install\n\nThe recommended way to install this library is [through Composer](https://getcomposer.org/).\n[New to Composer?](https://getcomposer.org/doc/00-intro.md)\n\nOnce released, this project will follow [SemVer](https://semver.org/).\nAt the moment, this will install the latest development version:\n\n```bash\ncomposer require react/dns:^3@dev\n```\n\nSee also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.\n\nThis project aims to run on any platform and thus does not require any PHP\nextensions and supports running on PHP 7.1 through current PHP 8+.\nIt's *highly recommended to use the latest supported PHP version* for this project.\n\n## Tests\n\nTo run the test suite, you first need to clone this repo and then install all\ndependencies [through Composer](https://getcomposer.org/):\n\n```bash\ncomposer install\n```\n\nTo run the test suite, go to the project root and run:\n\n```bash\nvendor/bin/phpunit\n```\n\nThe test suite also contains a number of functional integration tests that rely\non a stable internet connection.\nIf you do not want to run these, they can simply be skipped like this:\n\n```bash\nvendor/bin/phpunit --exclude-group internet\n```\n\n## License\n\nMIT, see [LICENSE file](LICENSE).\n\n## References\n\n* [RFC 1034](https://tools.ietf.org/html/rfc1034) Domain Names - Concepts and Facilities\n* [RFC 1035](https://tools.ietf.org/html/rfc1035) Domain Names - Implementation and Specification\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freactphp%2Fdns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freactphp%2Fdns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freactphp%2Fdns/lists"}