python requests ip address

Python Requests IP Address

If you are working with Python, you can use the Requests library to get the IP address of a website or server. Here's how:

Method 1: Using the socket module

You can use the socket module to get the IP address of a website:


import socket

url = 'https://www.example.com'
ip_address = socket.gethostbyname(url)

print(f'The IP address of {url} is {ip_address}')

The gethostbyname() method takes a hostname as input and returns its IP address.

Method 2: Using the Requests library

You can also use the Requests library to get the IP address of a website:


import requests

url = 'https://www.example.com'
response = requests.get(url)

print(f'The IP address of {url} is {response.url.split("//")[-1].split("/")[0]}')

The get() method of the Requests library returns a Response object. You can use the url attribute of this object to get the URL of the website. Then, you can extract the hostname from the URL using string manipulation and use the socket.gethostbyname() method to get the IP address.

Method 3: Using the urllib library

You can also use the urllib library to get the IP address of a website:


from urllib.parse import urlparse
import socket

url = 'https://www.example.com'
hostname = urlparse(url).hostname
ip_address = socket.gethostbyname(hostname)

print(f'The IP address of {url} is {ip_address}')

The urlparse() method of the urllib library returns a ParseResult object that contains the hostname of the website. You can use the socket.gethostbyname() method to get the IP address of the website.

These are some ways you can get the IP address of a website using Python.