Appearance
Finding local IP addresses using Python's stdlib
Here is a code snippet that uses the socket module from Python's standard library to find the local IP addresses of the host machine:
find the local IP addresses of the host machine using socket module
python
import socket
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# 10.255.255.255 is a broadcast address that forces the OS to select the default route interface
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
print(get_local_ip())This code creates a socket and connects to a non-local address using the socket's connect method. Then it retrieves the socket's own address using getsockname() method, which returns a tuple containing the IP address and the port number.
Note that you may have multiple IP addresses. If you want to see all IP addresses, use socket.gethostbyname_ex(socket.gethostname())[2].