- How to get an IP Address in Python
- Get IP Address from hostname in Python
- Get the IP Address of a website using a script in Python
- Get an IP address from the URL in Python
- Determine if the given IP Address is public or private using the ipaddress module in python
- IP Address validation in Python
- Extract MAC address in Python
- Python: get remote IP from HTTP request using the requests module
- Variables:
- How to Get Location Information of an IP Address Using Python
- Get your tools ready
- Get Location Information
- get_ip() function
- get_location() function
- Conclusion
How to get an IP Address in Python
To get the IP address in Python of your 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.
import socket h_name = socket.gethostname() IP_addres = socket.gethostbyname(h_name) print("Host Name is:" + h_name) print("Computer IP Address is:" + IP_addres)
- After writing the above code (python get the IP address), Ones you will print “IP_addres” then the output will appear as “ Host Name is: DESKTOP-AJNOCQ Computer IP Address is: 192.168.45.161 ”.
- First, import the socket module and then get the h_name using the socket.gethostname().
- Now, find the IP address by passing the h_name as an argument to the socket.gethostbyname() and store it in a variable. Print the IP address.
You can refer to the below screenshot:
Host Name is: DESKTOP-AJNOCQ Computer IP Address is: 192.168.45.161
Get IP Address from hostname in Python
Python gethostbyname() function accept the hostname as an argument and it will return the IP address of some of the website by using the socket module.
import socket IP_addres = socket.gethostbyname('pythonguides.com') print("IP Address is:" + IP_addres)
- After writing the above code (python get the IP address from hostname), Ones you will print “IP_addres” then the output will appear as “IP Address is: 104.28.20.90”.
- Here, socket.gethostbyname() will return the IP address of the website.
- If you are not in the same location as mine then you may get different IP addresses as output.
You can refer to the below screenshot:
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.
import socket host_name = input("Enter the website address: ") print(f'The IP address is: ')
- After writing the above code (python get the IP Address of a website using a script) first we will enter the website address, and then it will print the output as “ The food.com IP address is: 52.201.38.142”.
- Here, socket.gethostbyname(host_name) will return the IP address of the website “food.com”.
You can refer to the below screenshot:
Get an IP address from the URL in Python
Firstly, we have imported a socket module to get the IP address of a URL in Python. URL stands for Uniform Resource Locator. A URL is the address of the resource on the internet.
import socket url = "python.com" print("IP Address:",socket.gethostbyname(url))
- After writing the above code (python get an IP address from the URL) firstly, we will assign a URL to a variable.
- The variable acts as an argument for the socket.gethostbyname(url) and it will return the output as “ IP address: 3.96.23.237”.
You can refer to the below screenshot:
Determine if the given IP Address is public or private using the ipaddress module in python
- Private IP address – A private IP address is the address of your device that is 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 it’s unique for all. A public IP address is assigned by the Internet Service Provider(ISP).
To determine whether the given IP Address is public or private we will first import ipaddress module, and we will use the is_private method of the ipaddress module, which will test the address is allocated for private.
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'))
After writing the above code (determine if the given IP Address is public or private using the ipaddress module in Python) firstly, we will import the ipaddress module, and then we will use the is_private method of ipaddress. It will return the output as “Private Public”.
You can refer to the below screenshot:
IP Address validation in Python
If you want to check whether the given IP address is valid or not, use the socket module, and also we will use the function inet_aton() which will take only one argument.
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) ones you will print then the output will be “ Invalid IP address” because the given IP is not valid and 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:
Extract MAC address in Python
- A media access control address(MAC address) is 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 uuid.getnode() to extract MAC address of the computer.
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:
To get the MAC address in format form and with less complex way we will use getnode(), findall(), and re(). We need to import re and uuid module.
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) ones you will print then the output will be “ MAC address in less complex and formatted way is: 78:0c:b8:d4:d2:ca”. Using join element of getnode() after each 2 digits using regex expression will provide in a formatted way.
You can refer to the below screenshot:
You may like the following Python tutorials:
In this Python tutorial, we learned about Python get an IP Address. Also, We covered these below topics as:
- What is an IP Address and how to get an IP address in Python
- Python get IP Address from hostname
- Python get the IP Address of a website using a script
- Python get an IP address from the URL
- Determine if the given IP Address is public or private using the ipaddress module in python
- Python IP Address validation
- Python extract MAC address
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Python: get remote IP from HTTP request using the requests module
This is just a quick tip how to get the IP address from a http request using the requests module from Python’s standard library.
Variables:
Python 3.4.5 requests 2.18.1 urllib3 1.21.1
In order to get the IP, we need to use “stream” parameter to keep the connection open:
r = requests.get('http://exmaple.com', stream=True)
At this point only the response headers have been downloaded and the connection remains open until we access the Response.content
Here is the important part for this:
If you set stream to True when making a request, Requests cannot release the connection back to the pool unless you consume all the data or call Response.close. This can lead to inefficiency with connections. If you find yourself partially reading request bodies (or not reading them at all) while using stream=True, you should make the request within a with statement to ensure it’s always closed
We can see this in action using netstat. The Apache web server in this case, waits for the other side to shut down its half of the connection (FIN_WAIT2):
# netstat -entp Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name . tcp6 0 0 192.168.1.10:80 192.168.1.254:38610 FIN_WAIT2 0 0 -
With context manager, the socket is closed at both ends:
>>> with requests.get('http://exmaple.com/', stream=True) as r: . r.status_code . 404
# netstat -entp Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name . tcp6 0 0 192.168.1.10:80 192.168.1.254:44124 TIME_WAIT 0 0 -
Now, let’s get back to the main point here, requests.raw._original_response is a http.client.HTTPResponse instance, .fp is the socketfile, which here consists of a buffer wrapping a SocketIO object with the actual socket in the _sock attribute. So the original socket is available as requests.raw._original_response.fp.raw._sock and we can call .getpeername() on that:
>>> with requests.get('http://exmaple.com/', stream=True) as r: . r.raw._original_response.fp.raw._sock.getpeername()[0] . '192.168.1.10'
How to Get Location Information of an IP Address Using Python
Ashutosh Krishna
Sometimes you’ll need to know the location of an IP address, whether it’s your own or that of a site you’re using.
One use-case for this is when you want to send login information to users for your website.
In this article, we’re going to see how you can find the location of an IP address using Python.
Get your tools ready
To accomplish this goal, we’ll be using two APIs mentioned below:
- ipify: This API will help us know the IP address from where the request is coming.
- ipapi: This API will help us fetch location information for a particular IP address.
To interact with these APIs, we’ll be using the requests library in Python. If you’re new to APIs, make sure you check out this tutorial to learn about them.
You can install this library using the pip command like this:
Once the library is installed, we’re good to go!
Get Location Information
As we discussed, we’ll first fetch our IP address from the first API. Then we’ll make use of this IP address to fetch location information for this particular IP address. So, we’ll have two functions:
import requests def get_ip(): response = requests.get('https://api64.ipify.org?format=json').json() return response["ip"] def get_location(): ip_address = get_ip() response = requests.get(f'https://ipapi.co//json/').json() location_data = < "ip": ip_address, "city": response.get("city"), "region": response.get("region"), "country": response.get("country_name") >return location_data print(get_location())
In the above code, we have two functions – get_ip() and get_location() . Let’s discuss each of them separately.
get_ip() function
As per the API documentation of ipify, we need to make a GET request on https://api.ipify.org?format=json to get a JSON response that looks like this:
We store this response in a response variable which is nothing but a sort of Python dictionary with one key-value pair. So we returned the value of the key ip as response[«ip»] .
get_location() function
As per the API documentation of ipapi, we need to make a GET request on https://ipapi.co/// to get location information for a particular IP address. is replaced by the IP address and can be replaced with any of these – json , jsonp , xml , csv , yaml .
This function internally calls the get_ip() function to get the IP address and then makes a GET request on the URL with the IP address. This API returns a JSON response that looks like this:
We get a whole lot of data in the response. You can use whatever works for you. For this tutorial, we’ll just be using city , region and country . That’s why we created a dictionary called location_data and stored all the data inside it and returned the same.
At last, we call the get_location() function and print the output. Our output will look like this:
Conclusion
In this article, we learned how we can interact with web services to get location information for a particular IP address.
Thanks for reading! For more such articles, checkout my blog, iRead.