python get ip address

Python Get IP Address

If you are working on a project where you need to know your computer's IP address or the IP address of a website, Python can help you. Python has built-in libraries that enable you to get IP addresses easily. Here are a few ways:

Using the socket library:

The socket library is a low-level library in Python that provides an interface for network programming. You can use it to get the IP address of a website or your computer. Here is an example:


import socket

# Get local IP address
ip_address = socket.gethostbyname(socket.gethostname())
print("Local IP Address:", ip_address)

# Get website IP address
website = "www.example.com"
ip_address = socket.gethostbyname(website)
print(website, "IP Address:", ip_address)
            

Using the requests library:

The requests library is a popular library in Python used for sending HTTP requests. You can use it to get the IP address of a website. Here is an example:


import requests

website = "www.example.com"

# Send HTTP GET request and get website IP address
ip_address = requests.get(f"https://dns.google/resolve?name={website}").json()['Answer'][0]['data']
print(website, "IP Address:", ip_address)
            

Using the os library:

The os library is a standard library in Python used for interacting with the operating system. You can use it to execute shell commands and get the IP address of your computer. Here is an example:


import os

# Get local IP address
ip_address = os.popen('ipconfig | findstr IPv4').readline().split()[1]
print("Local IP Address:", ip_address)
            

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe