Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I get the IP address from a FQDN

If I have an FQDN e.g., www.google.com, how do I get the corresponding IP address?

like image 833
addicted-to-coding Avatar asked Dec 21 '22 19:12

addicted-to-coding


2 Answers

The easiest way to do this is socket.gethostbyname().

like image 156
Sven Marnach Avatar answered Jan 06 '23 04:01

Sven Marnach


You can use socket.getaddrinfo. That will give you the differents IP address associated with the name, and can also give you the IPv6 address.

From the documentation:

>>> import socket
>>> help(socket.getaddrinfo)
Help on built-in function getaddrinfo in module _socket:

getaddrinfo(...)
    getaddrinfo(host, port [, family, socktype, proto, flags])
        -> list of (family, socktype, proto, canonname, sockaddr)

    Resolve host and port into addrinfo struct.
>>> from pprint import pprint
>>> pprint(socket.getaddrinfo('www.google.com', 80))
[(2, 1, 6, '', ('74.125.230.83', 80)),
 (2, 2, 17, '', ('74.125.230.83', 80)),
 (2, 3, 0, '', ('74.125.230.83', 80)),
 (2, 1, 6, '', ('74.125.230.80', 80)),
 (2, 2, 17, '', ('74.125.230.80', 80)),
 (2, 3, 0, '', ('74.125.230.80', 80)),
 (2, 1, 6, '', ('74.125.230.81', 80)),
 (2, 2, 17, '', ('74.125.230.81', 80)),
 (2, 3, 0, '', ('74.125.230.81', 80)),
 (2, 1, 6, '', ('74.125.230.84', 80)),
 (2, 2, 17, '', ('74.125.230.84', 80)),
 (2, 3, 0, '', ('74.125.230.84', 80)),
 (2, 1, 6, '', ('74.125.230.82', 80)),
 (2, 2, 17, '', ('74.125.230.82', 80)),
 (2, 3, 0, '', ('74.125.230.82', 80))]

Note: gethostbyname is deprecated in C (and Python socket.gethostbyname is implemented with it) as it does not support IPv6 addresses, and getaddrinfo is the recommended replacement.

like image 22
Sylvain Defresne Avatar answered Jan 06 '23 04:01

Sylvain Defresne