To find the local IP addresses using Python, you can utilize the socket
library. The socket
library provides functions and classes for working with network connections. You can use the gethostname()
function to obtain the hostname of your machine and then use the gethostbyname_ex()
function to retrieve the IP addresses associated with that hostname. Here’s an example:
import socket
hostname = socket.gethostname()
ip_addresses = socket.gethostbyname_ex(hostname)[-1]
print(ip_addresses)
In the code above, we import the socket
library. We then use the gethostname()
function to obtain the hostname of the local machine and assign it to the variable hostname
. Next, we use the gethostbyname_ex()
function, passing in the hostname
, to retrieve a tuple containing the hostname and a list of IP addresses associated with it. We extract the IP addresses by indexing [-1]
to access the last element of the tuple.
Finally, we print the list of IP addresses using print(ip_addresses)
. The output will be a list of IP addresses assigned to the local machine, such as ['192.168.0.100', '10.0.0.1']
.
Note that a machine can have multiple IP addresses, so the gethostbyname_ex()
function returns a list of IP addresses associated with the hostname.
+ There are no comments
Add yours