I have a string representing a domain name. How can I get the corresponding IP address using Python 3.x? Something like this:
我有一个表示域名的字符串。如何使用Python 3.x获得相应的IP地址?是这样的:
>>> get_ip('http://www.*.com')
'64.34.119.12'
3 个解决方案
#1
7
>>> 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'])
#2
10
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()不支持IPv6。
- gethostbyname() uses the C call gethostbanme(), which is deprecated.
- gethostbyname()使用C调用gethostbanme(),它被弃用。
If these are problematic, use socket.getaddrinfo() instead.
如果有问题,可以使用socket.getaddrinfo()。
#3
6
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.
最简单的方法是使用socket.gethostbyname()。不过,这并不支持IPv6,并且基于已弃用的C调用gethostbanme()。如果您关心这些问题,您可以使用更通用的socket.getaddrinfo()。
#1
7
>>> 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'])
#2
10
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()不支持IPv6。
- gethostbyname() uses the C call gethostbanme(), which is deprecated.
- gethostbyname()使用C调用gethostbanme(),它被弃用。
If these are problematic, use socket.getaddrinfo() instead.
如果有问题,可以使用socket.getaddrinfo()。
#3
6
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.
最简单的方法是使用socket.gethostbyname()。不过,这并不支持IPv6,并且基于已弃用的C调用gethostbanme()。如果您关心这些问题,您可以使用更通用的socket.getaddrinfo()。