- How to Get the IPv4 IP Address of the Local Machine in Python
- Example 1: Using Using socket.gethostbyname() Method
- Example 2: Using socket module and socket.socket() and connect() and socket.getsockname() Method
- Example 3: Using socket module and socket.socket(), setsockopt(), connect() and socket.getsockname() Method
- 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 IP Address from Hostname
- Python Socket Module to Get IP Address from Hostname
- Python Script to Find Out the IP Address of a Website
- Error Scenarios with socket.gethostbyname()
How to Get the IPv4 IP Address of the Local Machine in Python
In this article, you will learn how to get the IPv4 IP address of the local machine in python. There are various ways to find the IPv4 IP address of the local machine in Python.
Here are some examples to get the IPv4 IP address of the local machine in python.
Example 1: Using Using socket.gethostbyname() Method
In this example, first, you need to import the socket module from the Python Standard Library and use the socket.gethostname() method to find the hostname and socket.gethostbyname() method to get the IPv4 IP address of a computer.
Here is the source code of the program to find the Hostname and the IPv4 IP address of the local computer in python.
Example 1: Using Using socket.gethostbyname() Method
# To get the IPv4 IP address of the local machine in Python # importing socket module import socket # getting the hostname by socket.gethostname() method hostname = socket.gethostname() # getting the IP address using socket.gethostbyname() method ip_address = socket.gethostbyname(hostname) # printing the hostname and ip_address print(f"Hostname: ") print(f"IP Address: ")
Example 2: Using socket module and socket.socket() and connect() and socket.getsockname() Method
In this example, we used the socket module and socket.socket() and connect() and socket.getsockname() Method to get the IPv4 IP address of the local machine in python.
Here is the source code of another approach to get the IPv4 IP address of the local machine in python.
Example 2: Using socket module and socket.socket() and connect() and socket.getsockname() Method
# To get the IPv4 IP address of the local machine using # Using socket module and socket.socket() and connect() # and socket.getsockname() Method in Python # Import Module import socket # Create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # connect to the server on local computer s.connect(("8.8.8.8", 80)) # Print Output print("HostName: ",s.getsockname()[0]) s.close()
Example 3: Using socket module and socket.socket(), setsockopt(), connect() and socket.getsockname() Method
In this example, we used the socket module and socket.socket() and connect() and socket.getsockname() Method to get the IPv4 IP address of the local machine in python.
Here is the source code of another approach to get the IPv4 IP address of a local machine in python.
Example 3: Using socket module and socket.socket(), setsockopt(), connect() and socket.getsockname() Method
# To get the IPv4 IP address of the local machine using # Using socket module and socket.socket(), setsockopt(), connect() # and socket.getsockname() Method in Python # Import Module import socket # Define a Function def getNetworkIp(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.connect(('', 0)) return s.getsockname()[0] # Print the Output print ("HostName: ",getNetworkIp())
I hope this article will help you to understand how to get the IPv4 IP address of the local machine in python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
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 IP Address from Hostname
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python socket module can be used to get the IP address from a hostname. The socket module is part of the Python core libraries, so we don’t need to install it separately.
Python Socket Module to Get IP Address from Hostname
Python socket module gethostbyname() function accepts hostname argument and returns the IP address in the string format. Here is a simple example in the Python interpreter to find out the IP address of some of the websites.
# python3.7 Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> import socket >>> socket.gethostbyname('journaldev.com') '45.79.77.230' >>> socket.gethostbyname('google.com') '172.217.166.110' >>>
Note: If the website is behind a load-balancer or working in the cloud, you might get a different result for the IP address lookup. For example, try to run the above command for google.com or facebook.com. If you are not in the same location as mine (India), chances are that you will get a different IP address as output.
Python Script to Find Out the IP Address of a Website
import socket hostname = input("Please enter website address:\n") # IP lookup from hostname print(f'The hostname> IP Address is socket.gethostbyname(hostname)>')
Here is another example to pass the hostname as a command-line argument to the script. The script will find the IP address and print it.
import socket import sys # no error handling is done here, excuse me for that hostname = sys.argv[1] # IP lookup from hostname print(f'The hostname> IP Address is socket.gethostbyname(hostname)>')
# python3.7 ip_address.py facebook.com The facebook.com IP Address is 157.240.23.35
Error Scenarios with socket.gethostbyname()
If the hostname doesn’t resolve to a valid IP address, socket.gaierror is raised. We can catch this error in our program using try-except block. Here is the updated script with exception handling for invalid hostname.
import socket import sys hostname = sys.argv[1] # IP lookup from hostname try: ip = socket.gethostbyname(hostname) print(f'The hostname> IP Address is ip>') except socket.gaierror as e: print(f'Invalid hostname, error raised is e>')
# python3.7 ip_address.py jasjdkks.com Invalid hostname, error raised is [Errno 8] nodename nor servname provided, or not known #
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us