在网络里与服务器通讯时,需要找到服务器的IP地址,但是人们输入的经常是域名地址,它们只是方便人类来记忆,但实际上还是需要IP地址的,这时就需要把域名转换为IP地址,在这个例子里使用协程来获取域名的IP地址,由于获取过程中会阻塞,使用协程就可以解决这个问题。
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
源码如下:
import asyncio
import logging
import socket
import sys
TARGETS = [
('blog.csdn.net', 'https'),
('baidu.com', 'https'),
('python.org', 'https'),
]
async def main(loop, targets):
for target in targets:
info = await loop.getaddrinfo(
*target,
proto=socket.IPPROTO_TCP,
)
for host in info:
print('{:20}: {}'.format(target[0], host[4][0]))
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop, TARGETS))
finally:
event_loop.close()
结果输出如下:
blog.csdn.net : 47.95.49.160
baidu.com : 220.181.57.217
baidu.com : 111.13.101.208
baidu.com : 123.125.114.144
python.org : 23.253.135.79