addicted-to-coding
addicted-to-coding

Reputation: 295

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?

Upvotes: 5

Views: 8378

Answers (3)

Xavier Combelle
Xavier Combelle

Reputation: 11235

Use socket.gethostbyname(hostname) see: http://docs.python.org/library/socket.html#socket.gethostbyname

Upvotes: 0

Sylvain Defresne
Sylvain Defresne

Reputation: 44593

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.

Upvotes: 6

Sven Marnach
Sven Marnach

Reputation: 602555

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

Upvotes: 7

Related Questions