How to Retrieve an IP Address in Python?

Estimated read time 2 min read

To retrieve an IP address in Python, you can use the socket module. Here’s an example:

import socket

# Retrieve the hostname
hostname = socket.gethostname()

# Retrieve the IP address
ip_address = socket.gethostbyname(hostname)

print(ip_address)

In this example, we use the socket.gethostname() function to retrieve the hostname of the current machine. Then, we pass this hostname to the socket.gethostbyname() function, which returns the corresponding IP address.

The socket.gethostbyname() function may return the IPv4 address associated with the hostname. If you want to retrieve the IPv6 address, you can use socket.getaddrinfo() function instead. Here’s an example:

import socket

# Retrieve the hostname
hostname = socket.gethostname()

# Retrieve the IP address
ip_address = socket.getaddrinfo(hostname, None, socket.AF_INET6)[0][4][0]

print(ip_address)

In this example, we use socket.getaddrinfo() with the socket.AF_INET6 argument to retrieve the IPv6 address associated with the hostname. The result is a list of tuples, and we extract the IP address from the first tuple.

Note that the IP address retrieved by these methods may correspond to the machine’s network interface or the network configuration. If you want to retrieve the IP address from an external service or based on a specific network interface, you may need to use additional libraries or methods tailored to your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply