Python has a built-in function to convert hostname to
IP addresses without having to external program. It is provided by the
socket module and you can get
IP address from hostname in
Python with this example;
$ ipython Python 3.7.0 (default, Jun 29 2018, 20:13:13) Type 'copyright', 'credits' or 'license' for more information IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
In : import socket
socket.gethostbynamewith hostname that you wish to resolve to IP address as parameter .
In : socket.gethostbyname('www.google.com') Out: '126.96.36.199'
Pythonscript that accepts
hostnameas parameter and outputs
IPaddress such as the following.
#!/usr/bin/env python3 import socket import sys hostname = sys.argv ip = socket.gethostbyname(hostname) print('Hostname: ', hostname, '\n' 'IP: ', ip)
$ python3 hostnametoip.py 'www.google.com' Hostname: www.google.com IP: 188.8.131.52
Sign up for Complete Python Bootcamp: Go from zero to hero in Python 3 and many other great courses on Udemy to learn more.
Learn Python like a Professional! Start from the basics and go all the way to creating your own applications and games!
Written by Mohd Shakir Zakaria.
Last updated on 2019-03-26.