Get to know Remote Server IPv4 Address in a Pythonic Way

Cover Image for Get to know Remote Server IPv4 Address in a Pythonic Way

Python is loved ❤️ by all sorts of people from Web Developers to Machine Learning Enginneers and Systems Programmers to Game Developers. So it's no surprise that Python can do Network Programming too.

Ever wondered about the IP addressess of the websites you visit on a daily basis but don't know where to start? If this strikes a chord with you then you are at the right place. So get right into the action.

All you need is less than 5 lines of Python Code

Let's get Started

Importing Socket

Python has a native Socket Module which does all the hard work for us

First step is importing Socket

import socket

use gethostbyname() Method

After importing the socket module, leverage the power of 'gethostbyname()' method by storing it in a variable and pass the remote server host or domain name of your interest(not the URL) as an argument.

Host => 'www.amazon.com' 
URL => 'https://www.amazon.com'

The gethostbyname Method usually accepts a single parameter ie.the host name and returns the IPv4 address as a string.

Socket.gethostbyname() Syntax

socket.gethostbyname(<hostname:str>)

And the real code

host = "www.google.com"
result = socket.gethostbyname("www.google.com")
print(result)

That's all you ever need

Here's the entire program

import socket
host = "www.google.com"
result = socket.gethostbyname("www.google.com")
print(result)

Output

You will get the IPv4 address printed as a string

142.251.2.105

This is one of the easiest ways to know about the IPv4 address of any server you like in a typical pythonic way and it can never get as simple as this.

See you all my fellow pythonistas