I want to expand on the answer of @john-colanduoni with more detail.
Get only the IPv6 address
To really get only the corresponding IPv6-address, you should try using socket.getaddrinfo.
>>> print(socket.getaddrinfo('www.microsoft.com', None, socket.AF_INET6)[0][4][0])
2a02:26f0:6a:288::356e
but beware, e.g. if there is no IPv6 AAAA-Record for the hostname, such as:
>>> print(socket.getaddrinfo('microsoft.com', None, socket.AF_INET6)[0][4][0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
you will get socket.gaierror: [Errno -2] Name or service not known
which is a subclass of OSError.
Btw. try using localhost
, the hostname
of your computer (if it's IPv6 enabled) or example.com
as the hostname argument.
Get the hostname from IPv6 address
A query for the PTR-Record would look like:
>>> print(socket.gethostbyaddr('2a00:1450:4001:81d::200e')[0])
fra15s18-in-x0e.1e100.net
since socket.gethostbyaddr is both IPv4 and IPv6 enabled.