Skip to content

Instantly share code, notes, and snippets.

@ofen
Last active April 1, 2020 15:46
Show Gist options
  • Save ofen/455ba117ba012906624c6143a4d0513e to your computer and use it in GitHub Desktop.
Save ofen/455ba117ba012906624c6143a4d0513e to your computer and use it in GitHub Desktop.
Simple asyncio socket DNS to IP resolver
import socket
import asyncio
from urllib.parse import urlsplit
async def get(url):
url = urlsplit(url)
hostname = url.hostname
if url.scheme == 'https':
port = url.port or 443
else:
port = url.port or 80
loop = asyncio.get_running_loop()
try:
# family, type, proto, canonname, sockaddr
info = await loop.getaddrinfo(hostname, port, proto=socket.IPPROTO_TCP)
return {
'name': url.hostname,
'ips': [sockaddr[0] for (family, type, proto, canonname, sockaddr) in info]
}
except socket.gaierror:
return {
'name': url.hostname,
'ips': []
}
if __name__ == '__main__':
names = [
'https://yandex.ru',
'https://ya.ru',
'https://google.com',
'https://youtube.com',
]
loop = asyncio.get_event_loop()
tasks = asyncio.gather(*[get(name) for name in names])
result = loop.run_until_complete(tasks)
loop.close()
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment