Определить свой ip python

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.
Читайте также:  Html proxy on line

You can refer to the below screenshot:

Python get IP Address

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:

Python get IP Address from hostname

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:

Python get the IP Address of a website using a script

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:

Python get an IP address from the URL

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:

Determine if the given IP Address is public or private using the ipaddress module in python

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:

Python IP Address validation

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:

Python extract MAC address

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:

Python extract MAC address

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

Получить IP-адреса в Python

  1. Используйте функцию socket.gethostname() для получения локального IP-адреса в Python
  2. Используйте функцию socket.getsockname() для получения локального IP-адреса в Python
  3. Используйте модуль 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

Источник

Python — Get IP Address from Hostname

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)>') 

Python Get Ip Address 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

Источник

Оцените статью