- 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
- Получить IP-адреса в Python
- Используйте функцию socket.gethostname() для получения локального IP-адреса в Python
- Используйте функцию socket.getsockname() для получения локального IP-адреса в Python
- Используйте модуль netifaces для получения локального IP-адреса в Python
- Сопутствующая статья — Python Network
- How to get a user’s IP address in Python
- Get an IP address in Python using the network socket interface
- Drawbacks to using sockets to get IP addresses in Python
- Get an IP address in Python using Abstract’s Geolocation API
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.
Получить IP-адреса в Python
- Используйте функцию socket.gethostname() для получения локального IP-адреса в Python
- Используйте функцию socket.getsockname() для получения локального IP-адреса в Python
- Используйте модуль netifaces для получения локального IP-адреса в Python
IP-адреса представляют собой последовательность цифр от 0.0.0.0 до 255.255.255.255, каждое число находится в диапазоне адресов от 0 до 255. Он может однозначно идентифицировать устройство в сети.
В этой статье мы получим локальные IP-адреса с помощью Python.
Используйте функцию socket.gethostname() для получения локального IP-адреса в Python
Мы можем использовать модуль socket в Python для создания сетевых подключений и отправки сообщений по сети.
Функция gethostname() возвращает имя хоста системы, под которым в настоящий момент выполняется Python.
import socket print(socket.gethostbyname(socket.gethostname()))
Используйте функцию socket.getsockname() для получения локального IP-адреса в Python
Если компьютерное устройство имеет маршрут, подключенный к Интернету, мы можем использовать функцию getsockname() . Он возвращает IP-адрес и порт в виде кортежа.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0])
Этот метод возвращает основной IP-адрес локального компьютера, то есть маршрут по умолчанию.
Мы также можем использовать эту функцию для создания определяемой пользователем функции, для которой не требуется маршрутизируемый доступ в Интернет.
import socket def extract_ip(): st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: st.connect(('10.255.255.255', 1)) IP = st.getsockname()[0] except Exception: IP = '127.0.0.1' finally: st.close() return IP print(extract_ip())
Вышеупомянутый метод работает на всех интерфейсах. Он также работает со всеми общедоступными, частными и внешними IP-адресами. Этот метод эффективен в Linux, Windows и OSX.
Используйте модуль netifaces для получения локального IP-адреса в Python
Модуль netifaces используется для предоставления информации о сетевых интерфейсах и их статусе.
Мы можем использовать его для получения IP-адреса локальной машины, как показано ниже.
from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, ['addr':'No IP addr'>] )] print(' '.join(addresses))
No IP addr No IP addr No IP addr No IP addr 192.168.0.104 127.0.0.1
Сопутствующая статья — Python Network
How to get a user’s IP address in Python
Because an IP address uniquely identifies every machine on a network, user IP addresses provide a useful way to track new and repeat visitors to your platform. Additionally, geolocating an IP address provides a way to obtain information on a user’s real-world location. This information can be used to improve your marketing by incorporating targeted advertisements and to improve the user experience by customizing your platform to their location.
This blog post covers how to identify a user’s IP address using Python. If you just want to identify your own, use our tool to see what is your IP address and location.
Get an IP address in Python using the network socket interface
One way to obtain a user’s IP address is by using Python’s native low-level networking interface, socket. A user’s IP address can be obtained by querying the device’s host name and then getting the associated IP address:
import socket # get the hostname of the socket hostname = socket.gethostname() # get the IP address of the hostname ip_address = socket.gethostbyname(hostname) print('IP Address:<>'.format(ip_address))
Drawbacks to using sockets to get IP addresses in Python
The primary drawback of this method is that its behavior may be platform dependent, since it relies on the operating system’s socket APIs. Although it is available on all modern Windows, MacOS, and Unix systems, this method may not work for older operating systems. Additionally, this approach may not work for devices that operate on less common platforms.
This approach also only provides the device’s IP address without any additional information from the IP. Although this data can be used to identify unique visitors to a platform, obtaining information about a user’s location or Internet provider requires queries to external databases.
Don’t reinvent the wheel.
Abstract’s APIs are production-ready now.
Abstract’s suite of API’s are built to save you time. You don’t need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that’s actually valuable for your app or business, and we’ll handle the rest.
Get an IP address in Python using Abstract’s Geolocation API
Abstract API offers a free geolocation API that obtains a user’s IP address and provides associated location information. A query to this API also provides information relevant to the user’s location, such as their timezone, currency, and regional flag. This information makes it possible to customize the user experience across your platform with just a single data call.
To obtain a user’s IP address and its associated location info, we can perform a simple call to Abstract’s Geolocation API:
import requests import json # Your API key, available from your account page YOUR_GEOLOCATION_KEY = 'your_key' # URL to send the request to request_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + YOUR_GEOLOCATION_KEY response = requests.get(request_url) result = json.loads(response.content) print(result) print('ip_address: <>'.format(result['ip_address']))
This approach provides a variety of geolocation information in addition to the user’s IP address. If this data was requested for a user with the IP address 139.130.4.5, the call would return the following information:
< 'ip_address': '139.130.4.5', 'city': 'Sydney', 'city_geoname_id': 2147714, 'region': 'New South Wales', 'region_iso_code': 'NSW', 'region_geoname_id': 2155400, 'postal_code': '1001', 'country': 'Australia', 'country_code': 'AU', 'country_geoname_id': 2077456, 'country_is_eu': False, 'continent': 'Oceania', 'continent_code': 'OC', 'continent_geoname_id': 6255151, 'longitude': 151.209, 'latitude': -33.8688, 'security': < 'is_vpn': False >, 'timezone': < 'name': 'Australia/Sydney', 'abbreviation': 'AEDT', 'gmt_offset': 11, 'current_time': '12:17:29', 'is_dst': True >, 'flag': < 'emoji': '🇦🇺', 'unicode': 'U+1F1E6 U+1F1FA', 'png': 'https://static.abstractapi.com/country-flags/AU_flag.png', 'svg': 'https://static.abstractapi.com/country-flags/AU_flag.svg' >, 'currency': < 'currency_name': 'Australian Dollars', 'currency_code': 'AUD' >, 'connection': < 'autonomous_system_number': 1221, 'autonomous_system_organization': 'Telstra Corporation', 'connection_type': 'Corporate', 'isp_name': 'Telstra Internet', 'organization_name': None >>
Abstract makes IP geolocation in Python simple.