ソケット通信を利用してURLからIPアドレスを取得してみましょう。
使用するモジュールはPython3.6標準のreとsocket。
コードは以下の通り。
# -*- coding: utf-8 -*-
import socket
import re
def url_to_domain(url):
try:
reg = r'https?://([\w\-.]+)'
return re.search(reg, url).group(1)
except:
return False
def domain_to_ipaddress(domain):
try:
return socket.gethostbyname(domain)
except:
return False
if __name__ == "__main__":
urls = ['https://www.google.com',
'http://www.ikedahayato.com/20190110/78056845.html',
'http://weblog.horiemon.com/100blog/48821/']
for url in urls:
print('-------------')
print(url)
domain = url_to_domain(url)
print(domain)
ipaddress = domain_to_ipaddress(domain)
print(ipaddress)
結果はこちら。
-------------
[https://www.google.com](https://www.google.com)
www.google.com
172.217.25.100
-------------
[http://www.ikedahayato.com/20190110/78056845.html](http://www.ikedahayato.com/20190110/78056845.html)
www.ikedahayato.com
203.104.130.159
-------------
[http://weblog.horiemon.com/100blog/48821/](http://weblog.horiemon.com/100blog/48821/)
weblog.horiemon.com
99.84.138.23
まず正規表現でurlからドメイン部を抽出。
次にソケット通信でIPアドレスを取得。
いろいろ試してみた結果、
ドメインが異なっていても同じサーバー上にある可能性に注意。