10

I have a string representing a domain name. How can I get the corresponding IP address using Python 3.x? Something like this:

>>> get_ip('http://www.stackoverflow.com')
'64.34.119.12'
Honest Abe
  • 8,430
  • 4
  • 49
  • 64
snakile
  • 52,936
  • 62
  • 169
  • 241
  • 2
    possible duplicate of [How to resolve DNS in Python?](http://stackoverflow.com/questions/3837744/how-to-resolve-dns-in-python) – Dan Grossman Jan 27 '11 at 10:17

4 Answers4

11
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
>>> import socket
>>> socket.gethostbyname('cool-rr.com')
'174.120.139.162'

Note that:

  • gethostbyname() doesn't work with IPv6.
  • gethostbyname() uses the C call gethostbanme(), which is deprecated.

If these are problematic, use socket.getaddrinfo() instead.

snakile
  • 52,936
  • 62
  • 169
  • 241
Ram Rachum
  • 84,019
  • 84
  • 236
  • 374
11
>>> import socket

>>> def get_ips_for_host(host):
        try:
            ips = socket.gethostbyname_ex(host)
        except socket.gaierror:
            ips=[]
        return ips

>>> ips = get_ips_for_host('www.google.com')
>>> print(repr(ips))
('www.l.google.com', [], ['74.125.77.104', '74.125.77.147', '74.125.77.99'])
snakile
  • 52,936
  • 62
  • 169
  • 241
Shoshan
  • 321
  • 1
  • 4
7

The easiest way is to use socket.gethostbyname(). This does not support IPv6, though, and is based on the deprecated C call gethostbanme(). If you care about these problems, you can use the more versatile socket.getaddrinfo() instead.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

Here is full example, how you can get a website's IP address using Python

import urllib.parse
import socket
import dns.resolver

def get_ip(target):
    try:
        print(socket.gethostbyname(target))
    except socket.gaierror:
        res = head(target, allow_redirects=True)
        try:
            print(r.headers['Host'])
        except KeyError:
            parsed_url = urllib.parse.urlparse(target)
            hostname = parsed_url.hostname
            try:
                answers = dns.resolver.query(hostname, 'A')
                for rdata in answers:
                    print(rdata.address)
            except dns.resolver.NXDOMAIN:
                print('ip not found')

get_ip('example.com')
jak bin
  • 380
  • 4
  • 8