Python запрос ip адреса

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:

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”.
Читайте также:  Variable declared in python

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.

Читайте также:  C-Driver Manager

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.

Источник

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 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.

Читайте также:  Docker composer php apache

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.

Источник

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