python get public ip address with code examples

Introduction

Python is a versatile programming language that has been widely adopted by developers across different domains for its ease of use, efficiency, and flexibility. One of the most common tasks in networking is to obtain the public IP address of a device. In this article, we will explore different methods to retrieve the public IP address using Python.

What is a Public IP Address?

An Internet Protocol (IP) address is a unique numerical identifier assigned to every device on a network. There are two types of IP addresses: private and public. A private IP address is allocated within a private network and is not accessible to the internet. On the other hand, a public IP address is the IP address assigned by the Internet Service Provider (ISP) to the router or modem that connects a private network to the internet.

Why Get Public IP Address?

Knowing the public IP address of a device is important for many networking tasks such as remote access, server administration, and troubleshooting. It can also be useful for geolocation applications as the public IP address can be used to identify the approximate physical location of a device.

Methods to Retrieve Public IP Address

Here are some of the methods that can be used to retrieve the public IP address of a device in Python:

  1. Using urllib Library

Python’s urllib library provides a simple way to access URLs. We can use this library to retrieve the public IP address from a web service that returns the IP address in plain text.

import urllib.request

ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

print(ip)

In the above code, we are using Python's urllib.request.urlopen method to access the URL https://ident.me that returns the public IP address in plain text format. The read() function then retrieves the contents of the URL as bytes, which is then decoded into a string format using the decode() function. Finally, the retrieved IP address is printed to the console.

  1. Using Requests Library

The Requests library is one of the most popular libraries used for making HTTP requests in Python. We can use this library to retrieve the public IP address from a web service that returns the IP address in JSON or XML format.

import requests

ip = requests.get('https://api.ipify.org?format=json').json()['ip']

print(ip)

In the above code, we are using Python's requests.get method to access the URL https://api.ipify.org that returns the public IP address in JSON format. The json() function then parses the returned JSON response, and we retrieve the IP address by accessing the 'ip' key. Finally, the retrieved IP address is printed to the console.

  1. Using Socket Library

Python's socket library is a low-level networking library that allows us to establish communication between client and server applications. We can use this library to retrieve the public IP address of a device by connecting to a remote host and getting the socket connection address.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
s.close()

print(ip)

In the above code, we are using Python's socket library to establish a UDP socket connection to the Google Public DNS server at IP address '8.8.8.8' on port 80. We retrieve the socket connection address by calling the getsockname() function, which returns a tuple containing the address and port of the local socket. Finally, we retrieve the IP address from the tuple and print it to the console.

Conclusion

In this article, we have explored different methods to retrieve the public IP address using Python. The urllib, requests, and socket libraries are all effective ways to obtain the public IP address from various web services and socket connections. Knowing the public IP address of a device can be useful for many networking tasks such as remote access, server administration, and troubleshooting.

let's dive a bit deeper into the previous topics we covered.

Using urllib Library

The urllib library in Python is a module that allows developers to access URLs and send HTTP/HTTPS requests programmatically. The library provides a simple way to read data from web pages, and we can use it to obtain the public IP address by accessing a web service that returns the IP address in plain text format.

In the code example, we used the urllib.request.urlopen method to access the URL https://ident.me, which returns the public IP address in plain text format. We then retrieved the contents of the URL as bytes using the read() function. Finally, we decoded the bytes into a string format using the decode() function, and we printed the retrieved IP address to the console.

Using Requests Library

The Requests library in Python is an HTTP library that allows developers to send HTTP/HTTPS requests programmatically. The library is known for its simplicity and the user-friendly syntax, making it easier for developers to send requests and handle responses.

In the code example, we used the requests.get() function to access the URL https://api.ipify.org that returns the public IP address in JSON format. We then parsed the returned JSON response using the json() function, and we retrieved the IP address by accessing the 'ip' key. Finally, we printed the retrieved IP address to the console.

Using Socket Library

The Socket module in Python is a low-level networking library that provides a simple way to establish communication between client and server applications over a network. Sockets are used to handle the actual communication between client and server applications.

In the code example, we used the socket.socket() function to create a socket object, and we specified the AF_INET socket family and SOCK_DGRAM socket type. We then established a UDP socket connection to the Google Public DNS server at IP address '8.8.8.8' on port 80, and we retrieved the socket connection address using the getsockname() function. Finally, we retrieved the IP address from the tuple that contains the address and port of the local socket, and we printed the retrieved IP address to the console.

Conclusion

Knowing the public IP address of a device is crucial in networking and can be useful for many applications such as remote access, server administration, and troubleshooting. In Python, we can use libraries such as urllib, requests, and socket to obtain the public IP address using different methods. Each method has its advantages and disadvantages, and we need to choose the right method that suits our needs. Whether we choose the urllib method, requests method, or socket method, we can obtain the public IP address with ease using Python.

Popular questions

  1. What is a public IP address?
    A: A public IP address is the IP address assigned by the internet service provider to the router or modem that connects a private network to the internet.

  2. Why is it important to know the public IP address of a device?
    A: Knowing the public IP address of a device is important for many networking tasks such as remote access, server administration, and troubleshooting. It can also be useful for geolocation applications as the public IP address can be used to identify the approximate physical location of a device.

  3. Which libraries can be used to retrieve the public IP address in Python?
    A: The libraries that can be used are: urllib, requests, and socket

  4. What is the difference between requests and urllib in Python?
    A: Requests is a high-level HTTP library while urllib is a low-level HTTP library. Requests provides user-friendly syntax for sending HTTP requests while urllib requires more complex syntax for sending HTTP requests.

  5. What method can we use to retrieve the public IP address of a device using the Socket library in Python?
    A: We can use the connect() method to establish a TCP/IP socket connection to a remote host, and then the getsockname() method to retrieve the socket connection address which contains the local IP address of the device.

Tag

Networking

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top