How to get an IP from a URL in Python? [+5 Examples]

In this Python tutorial, you will learn what an IP Address is and how to get an IP from a URL in Python using different methods with examples.

Getting an IP from a URL in Python is fundamental in networking and web development. I will also explain the topics below :

  • How to get an IP Address in Python
  • Get an IP Address from a hostname in Python.
  • How to get the IP Address of a website using a script in Python
  • Determine if the IP Address is public or private using the ipaddress module in Python.
  • Python IP Address validation
  • Extract MAC address in Python.

What is an IP Address

  • IP stands for Internet Protocol Address. It is the address of your network hardware, connecting your computer with other devices on your network and worldwide.
  • An IP Address is made up of characters or numbers like 508.543.12.514. All devices connected to an internet connection have a unique IP Address.

Get an IP from a URL in Python

To get an IP from a URL in Python, We can use the socket module with different functions like getaddrinfo(), and gethostbyname_ex().

Let’s see them all one by one in detail with example:

1. Get IP from URL Python using the socket module

Python has a built-in socket module that provides a straightforward method to resolve hostnames to IP addresses. We will use the socket.gethostname() function to get an IP from a URL in Python.

Here’s a simple example:

import socket

def get_ip_address(url):
    try:
        ip_address = socket.gethostbyname(url)
        return ip_address
    except socket.error as err:
        print(f"Error: {err}")

url = "google.com"
ip = get_ip_address(url)
print(f"The IP address of {url} is {ip}")

We have created a function named get_ip_address(url). Here, we have used the socket.gethostbyname(url) function that gives the IP address corresponding to the URL.

READ:  Python Get Unique Values in List

If the URL is invalid, the function raises a socket.error in Python. So, we have used try and except block to handle such cases.

def get_ip_address(url):
    try:
        ip_address = socket.gethostbyname(url)
        return ip_address
    except socket.error as err:
        print(f"Error: {err}")

Output:

The IP address of google.com is 142.250.183.238

The output can be seen in the screenshot below after executing the code in PyCharm.

get an IP from a URL in Python

2. Python get IP from URL using socket.getaddrinfo() function

We can also use the socket.getaddrinfo() function in Python returns a list of tuples containing lots of information about each family available for the given hostname.

import socket

def get_ip_address(url):
    try:
        addr_info = socket.getaddrinfo(url, None)
        ip_address = addr_info[0][4][0]
        return ip_address
    except socket.error as err:
        print(f"Error: {err}")

url = "www.google.com"
ip = get_ip_address(url)
print(f"The IP address of {url} is {ip}")

The socket.getaddrinfo() will translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service in Python.

Here, we are extracting the IP address from the tuple returned by the function in Python.

addr_info = socket.getaddrinfo(url, None)
ip_address = addr_info[0][4][0]
return ip_address

Output:

The IP address of www.google.com is 142.250.67.36

The screenshot below shows the code implemented in the PyCharm editor.

get ip from url python

3. Python get all IP addresses of the host using the socket.gethostbyname_ex() function

The socket.gethostbyname_ex() function is similar to the socket.gethostbyname() in Python, but it also returns aliases and IP addresses associated with the given hostname.

Here’s how we can use it to get an IP from a URL in Python:

import socket

def get_ip_address(url):
    try:
        _, _, ip_addresses = socket.gethostbyname_ex(url)
        return ip_addresses[0]
    except socket.error as err:
        print(f"Error: {err}")

url = "google.com"
ip = get_ip_address(url)
print(f"The IP address of {url} is {ip}")

Output:

The IP address of google.com is 142.250.193.110

Upon executing the code in Pycharm, the resulting output is displayed in the screenshot below.

python script to get ip address from hostname

How to get an IP Address in Python

To get an IP address in Python of our computer, we need to import the socket library, and then we can find the IP address of the computer, laptop, etc, and they have their unique IP address.

Consider the following example:

import socket
def get_local_ip_address():
    try:
        hostname = socket.gethostname()
        ip_address = socket.gethostbyname(hostname)
        return ip_address
    except socket.error as err:
        print(f"Error: {err}")

local_ip = get_local_ip_address()
if local_ip:
    print(f"The local IP address of this laptop is {local_ip}")
else:
    print("Failed to retrieve the local IP address")
  • First, import the socket module and get the hostname using the socket.gethostname() function in Python.
  • Find the IP address by passing the hostname as an argument to the socket.gethostbyname() function in Python and store it in a variable. Print the IP address.
READ:  Could not convert string to float in Python

Output:

The local IP address of this laptop is 192.168.0.116

You can refer to the screenshot below. Here, I have shown my actual IP address as well as the result.

python get ip address

Get IP Address from hostname in Python

Python gethostbyname() function accepts the hostname as an argument, and it will return the IP address of some of the websites by using the socket module.

Example:

import socket

IP_addres = socket.gethostbyname('pythonguides.com')
print("IP Address is:" + IP_addres)
  • Here, socket.gethostbyname() will return the IP address of the website.
  • You may get different IP addresses as output if you are not in the same location as mine.

You can refer to the below screenshot:

python get my ip

Get the IP Address of a website using a script in Python

Here, we will ask a user to enter the website address and then print the IP address of that website.

Example:

import socket

host_name = input("Enter the website address: ")
print(f'The {host_name} IP address is: {socket.gethostbyname(host_name)}')
  • Here, socket.gethostbyname(host_name) will return the IP address of the website “food.com.”

You can refer to the below screenshot:

Python get the IP Address of a website using a script

Determine if the given IP Address is public or private using the ipaddress module in Python

  • Private IP address – A private IP address is your device’s address connected to the home or business network. This IP address cannot be accessed from devices outside your home or business network.
  • Public IP address – A public IP address is an address that is used to communicate outside the network. This IP address connects you to the world and is unique for all. The Internet Service Provider(ISP) assigns a public IP address.

To determine whether the given IP Address is public or private in Python, we will first import the ipaddress module and use the is_private method in Python, which will test whether the address is allocated for private.

Here’s a simple example:

from ipaddress import ip_address

def IP_address(IP: str)-> str:
    return "Private" if (ip_address(IP).is_private) else "Public"

if __name__ == '__main__':
    print(IP_address('127.0.0.1'))
    print(IP_address('3.96.23.237'))

Firstly, we will import the ipaddress module and then use the is_private method in Python. It will return the output as “Private” or “Public.”

You can refer to the below screenshot:

python ipaddress

IP Address Validation in Python

If you want to check whether the given IP address is valid in Python, use the socket module, and we will also use the function inet_aton() function, which will take only one argument.

READ:  How to split a string with multiple delimiters in Python

For example:

import socket

IP = '127.0.0.2561'

try:
   socket.inet_aton(IP)
   print("Valid IP address")
except socket.error:
   print("Invalid IP")

After writing the above code (python IP Address validation), the output will be “ Invalid IP address” once you print because the given IP is not valid; hence, the except block will be executed. If the given IP address is valid then it will return a valid IP address.

You can refer to the below screenshot:

Python IP Address validation

Extract MAC address in Python

  • A media access control address(MAC address), also known as a physical address, is a unique identifier assigned to the network interface card(NIC) of the computer.
  • MAC address is a hardware identification number that uniquely identifies each device on a network.
  • NIC helps in the connection of a computer with computers in the network.

To extract MAC address we will first import uuid module, and then we will use the uuid.getnode() to extract the MAC address of the computer.

Presented below is a simple example:

import uuid

print(hex(uuid.getnode()))

After writing the above code (python extract MAC address) ones you will print “hex(uuid.getnode())” then the output will be “ 0x780cb8d4d2ca ”. But the visible output is not in format for and complex too.

You can refer to the below screenshot:

Python extract MAC address

To get the MAC address in format form and in a less complex way, we will use getnode(), findall(), and re(). We need to import re and uuid modules in Python.

Example:

import re, uuid
print(" MAC address in less complex and formatted way is :", end="")
print(':'.join(re.findall('..', '%012x' %uuid.getnode())))

After writing the above code (Python extract MAC address), you will print the output “ MAC address in a less complex and formatted way is 78:0c:b8:d4:d2:ca”. Using the join element of getnode() after each 2 digits using regex expression will provide in a formatted way.

You can refer to the below screenshot:

python get mac address

Conclusion

Here, I have explained how to get an IP from a URL in Python using different functions from the socket module. We have used socket.gethostbyname(), getaddrinfo(), and gethostbyname_ex() function.

I hope you understand all the methods in detail, and will use them in the code as per requirement.

You may like the following Python tutorials: